Create a master Model and Controller in Yii2

In this article I discuss how to create a master Model and Controller using the Yii2 framework. Why would you want to do this? A master Model and Controller provides a place to put higher level methods which contain functionality that you want to use in your Models and Controllers. Rather than repeating code across multiple Models and Controllers put the code in the master Model and / or Controller and access it from the standard Models and Controllers. You can also override standard Yii2 Model and Controller functionality with your own altering the fundamental way Yii2 works without having to alter the core Yii2 files.

The master Model and Controller are classes that extend from the following …

  1. \yii\db\ActiveRecord – for Models
  2. \yii\web\Controller – for Controllers

Yii2 also contains another type of Model, this Model is used for defining data with no database table. This kind of model is useful for forms which do not need to use a database table but still need the inherit functionality within Yii2 Models like Validations. Although I will not be extending this second type of Model in this article you can use what you learn from this article to extend it yourself if you wish. The class for this Model is located at \yii\base\Model.

The diagram below shows what we are trying to accomplish …

Master Model and Controller

The “From” part of the diagram shows what the Yii2 software application without a master Model and Controller. The “To” part of the diagram shows the addition of the Master and Controller. Notice how the original ActiveRecord is called “ActiveRecord” and so is our master Model. Also the original Controller is called “Controller” and so is our master Controller. You do not need to worry about this as they exist in different Namespaces. You can call the master Model and / or Controller something different if you prefer.

Now lets look at the code to add the master Model and Controller to a Yii2 application. Create 2 new files one named “ActiveRecord.php” and one named “Controller.php” and place them inside the “components” folder inside your Yii2 application.

Now inside the files write the following code …

ActiveRecord.php

Controller.php

Now when it comes to creating your standard Models and Controllers you can extend from the master Model and Controller like follows …

Book.php (Model) …

BookController.php (Controller) …

The above 2 files would reside in the standard “models” and “controllers” folders.

Now any methods you want to use across multiple Models and Controllers can be placed inside the master Model and Controller. These will be accessible from the lower level Models and Controllers exactly as they would be in any extended PHP class. Also as mentioned earlier you can override standard Yii2 Model and Controller methods in the master Models and Controllers thus allowing you to alter the way Yii2 works without having to alter the core Yii2 files.

Remember if you wish to override the constructor in the master Model or Controller to call the parent constructor inside the override constructor.

A master Model and Controller are PHP classes I create for all my Yii2 applications. They are infinitely useful for the already mentioned above reasons.

My new way and correct way of coding Controllers

I have been using frameworks for a number of years with the Yii2 framework being my framework of choice at the present time. When it comes to defining how an application should be structured in terms of Controllers and their methods i was always one to put methods wherever I felt it made sense to put one.

For example my UserController would consist of index, view, create, update, delete, login, logout, lostpassword methods. This made sense at the time. Any action methods that relate to user functionality could go in the UserController. However all the time I was doing this I was aware that some developers and articles on the internet point to the fact that Controllers should only have certain methods within them, namely the standard CRUD methods and nothing else.

So one day I decided to follow that train of thought and start writing my controllers to only have the following methods, index, view, create, update, delete. These methods serve the following purpose …

  1. Index – view all records in a grid view
  2. View – view single record in a detail view
  3. Create – create form and submission code for single record
  4. Update – update form and submission code for single record
  5. Delete – delete a single record

I am aware that I could even get rid of the index and just handle the “view all” and “view single record” through the single Controller method of “view” by checking to see whether an ID parameter has been provided to the method however I thought I would keep them separate.

I am quite pleased by how the new structure has turned out in that it makes my Controller less bulky with code and it gives a much more structured neat and clean feeling to my code and software application.

So you might be wondering what happened to my UserController and the extra methods that where described earlier i.e. login, logout, lostpassword etc. Well using the new system they can be broken down as follows …

UserController

  1. Index – view all users in the system
  2. View – view single users details
  3. Create – create a user
  4. Update – update a user
  5. Delete – delete a user

LoginController

  1. Create – log the user in
  2. Delete – log the user out

LostPasswordController

  1. Create – send the user a link to change the users password
  2. Update – process the clicked link and change the users password

So it is possible to do this, basically the Controllers within the software application now take more definition by having the Controllers named after the type of event the user is wanting to make within the software application and placing less emphasis on the Controllers methods providing the definition. I really like my new way of coding my Controllers and I intent to stick to this method for the foreseeable future.

Yii 1 to Yii 2 differences and enhancements part 3

As a continuation on from Yii 1 to Yii 2 differences and enhancements part 3 I have noted some more differences between the 2 versions of the Yii framework …

Scopes

In Yii 1 Scopes where defined as arrays. The key of the array was setup as the scope name and the value of the array was the additional piece of code that would be appended to the select query when using the scope.

In Yii 2 Scopes are defined by overriding the find() method inside a model. The overridden find() method returns a new ActiveQuery object which is defined in a separate class.

Essentially the new method uses the components that are already inherent within Yii2 to build the Scope i.e. the ActiveQuery class. The methods of the class become the items in the array in the Yii1 way of doing Scopes. This is a neater way of writing the Scopes than using the old Yii1 method of creating Scopes and with the fact that it is using the inherent functionality of the ActiveQuery class I would presume more powerful.

Authentication rules

A small difference but an extremely powerful one has been the addition of the “matchCallback” option to Yii2’s AccessControl system. In Yii1 to do user permissions a hierarchy of permissions would be setup with bizRules assigned to those permissions. The bixRules where pieces of code that needed to evaluate to true to allow the user to access what permission the user was trying to access. Permissions where assigned to controller actions.

So the application would get the controller action the user was trying to access, the application would then ask does the user have this permission and does this permission evaluate to true. The bizRules where written in code but where then stored in the database along with the rest of the permissions in a set of 3 tables. AuthAssignment, AuthItem and AuthItemChild.

Well you can still do all this with Yii2 but with the introduction of the “matchCallback” option I can skip most of this. I can now assign my bizRule directly to a controller action method. So I can choose not to create a permission hierarchy with all associated bizRules, also using the “matchCallback” allows me to create my own permission system more easily.

Bootstrap components

In Yii2 the components are styled using Bootstrap out of the box also Yii2 has some wrappers for various other Bootstrap components. In Yii1 this functionality was only gained through the use of plugins like YiiStrap and YiiBooster. Now this comes out of the box and is fully integrated as standard. This brings me to my next point below.

Kartik plugin

Yii1 had YiiStrap and YiiBooster. Yii2 has the Kartik plugins, I will not say much about this other than providing a link …

http://demos.krajee.com/

The additional functionality this plugin provides is huge, timepickers, datepickers, enhanced datagrids, enhanced detail views, sliders, tag selectors, menus, icons, labels there is simple too much to name here. The additional value this plugin provides cannot be easily listed here.

This concludes part 3 of Yii 1 to Yii 2 differences and enhancements.

Four rooms drinks cabinet

I was watching Four Rooms on television today. For those who do not know Four Rooms is a television program were contestants bring in luxury items and a group of millionaire dealers bid on the items.

four-rooms

So a guy comes in with a drinks cabinet he has custom built using a special Canadian mahogany. He states that the cabinet took him 1 month to build and he obviously has to pay for his materials.

Anyways to cut a long story short he visits the 4 dealers. Some of the dealers state that they like the piece, some of the dealers state that they can appreciate his craftsmanship and furniture making skills.

All seems well! Until the dealers start making their offers that is!

The guy states he wants £8000 for it and no dealer offered him anywhere near that. The offers the dealers were making ranged from £1000 to £1500.

What gets me is that they have complimented him on his craftsmanship and skills but they basically insult the guy by making such a low offer.

At the dealers top offer, if we say the furniture materials cost £500 which is basically going to be the absolute minimum, who knows? The materials could have cost £1000 right? And then we take the fact that it took him 1 month to make.

So that is £1500 minus £500 divided by 4 weeks, that makes the craftsman £250 a week at the most.

The dealers have flattered him by saying they like his craftsmanship and then offered him the same price you would buy a mass produced commodity drinks cabinet from IKEA or similar.

From this we can gather that the dealers have no real appreciation of his labor, no appreciation of his craftsmanship and seem to think that a custom built drinks cabinet is on a par with a commodity item.

Absolutely ridiculous!

Yii 1 to Yii 2 differences and enhancements part 2

I wrote about Yii 1 to Yii 2 differences and enhancements some time ago and now I am going to carry on from that article to discuss more differences and enhancements I have found since moving to the Yii 2 framework from the Yii 1 framework …

Relations

In Yii 1 relationships where defined in the relations method. The relations methods is a method that returns an array of data specifying the relations the model has and data relevant to those relations.

The array is used to create the relations as model properties.

In Yii 2 relations are defined in “magic methods” as follows …

I prefer the Yii 2 way of using the magic methods because it allows you to write additional code in the method that defines the relation. This could come in handy in unique scenarios where custom code is needed to handle the relationship. I also think the Yii 2 method is more in line with the PHP language as a whole than the Yii 1 way of defining relations.

Validations

Yii 2 has more validation options than Yii 1 and has introduced further options the validations themselves which make creating these sorts of validations a lot more streamlined. Both Yii 1 and Yii 2 validations are defined as arrays. With the added bonus of the later version of PHP language in the Yii 2 framework the arrays in Yii 2 look more streamlined.

For example rather than this …

They are like this …

They look much better.

Yii 2 introduces the new “when” option and thanks to PHP callback functions we can now write a validation like so …

This will only require the “name” attribute when the “complete” attribute is true. In Yii 1 this validation would have had to have been written as a custom validation method which is a real pain.

That is it for now, another update to come soon.

The treadmill desk has been created

I wrote the following post some time ago about me buying a new treadmill and why I brought a normal treadmill as opposed to buying a treadmill desk …

http://www.jamesbarnsley.com/site/2014/11/29/new-treadmill-way-on-its-way/

I mentioned at the bottom of the post that I may make my very own treadmill desk as the standard treadmill desks that are available only go up to a certain speed which is quite slow and I did not want to reach a plateau with my weight loss.

Normal treadmills can go much faster than the treadmill desks that you can buy and as I may need to turn up the intensity of my workouts I opted for getting a normal treadmill rather than a treadmill desk as both are expensive and I could only get one or the other.

For those of you who do not know a treadmill desk is half desk and half treadmill which you can buy from professional companies which produce them. They look like this …

treadmill-desk-consumer

Since the time of purchasing my treadmill I have noticed how easy it is to get bored whilst walking on it and I liked the idea of having a desk so I could go on my laptop whilst I am walking. Anyways I decided to make my own and with the help of my Dad we got this assembled …

treadmill-desk

Ladies and gentlemen, my very own treadmill desk! As you can see it is created from a couple of wall brackets from B&Q and a piece of “offcut” wood purchased from the industrial estate timber yard next door to where I work.

“Offcut” wood is the throw away wood that was left over when they cut the wood for their customers etc, this is generally sold for a couple of pounds. The whole desk cost me around £20 to make and it is detachable from the wall and can be stored away if so desired.

The angle of the photo I have taken makes the desk look quite thin but the photo does not actually do it justice as it plenty big enough to put my laptop on as well as some other stuff.

So far I am enjoying my treadmill desk as it means I can do more walking without getting bored. I can even do tasks whilst walking, in fact this blog post was written whilst I was walking on my treadmill desk.

Yii 1 to Yii 2 differences and enhancements part 1

A number of months ago I made the switch to the Yii 2 framework from the Yii 1 framework. My intent in this post is to outline some of the differences and enhancements I have found from switching to the latest Yii framework.

A framework is a set of code written to help in common programming tasks for example handling data, creating forms and data tables etc.

When I first started programming I did not use a framework as I did not understand the benefits properly of using a framework. The above tasks would have been written from scratch and would have essentially duplicated code that was already out there for solving these common tasks.

When I first started using a framework it made my life much easier and the end product was of a better quality to time ratio than not using a framework. The same quality could be achieved without the use of a framework but would take longer and the programmer would be essentially writing code for common problems that already have a solution.

I would also like to mention that frameworks provide a consistent structure to the code that a programmer writes so that one way of solving a problem at one end of the code would be the same way the problem was solved at another end of the code. This makes it easier for other programmers to understand the code base.

After using the Yii 2 framework here are some of the differences and enhancements that I have found …

User Identity

In Yii 1 a “User identity” is a class that extends “UserIdentity” and handles the authentication and identity of the logged in user. I would create a class that extends “UserIdentity” create some predefined methods and let Yii handle the authentication.

In Yii 2 a similar approach is used except I do not create an extended “UserIdentity” class but instead I “implement” “IdentityInterface” in my User class. In Yii 1 I would have a “UserIdentity” class and a “User” class, in Yii 2 I just have the “User” class. Similar to Yii 1 I create some predefined methods in my “User” class and let Yii handle the authentication.

Active Record

Active Record has some key differences going from the Yii 1 framework to the Yii 2 framework. In Yii 1 Active Record was used like so …

Or …

Or …

In Yii 2 Active Record is used as follows …

Or …

Or …

Basically in Yii 1 there where a lot of methods that where created for specific purposes “findAll”, “findByPK”, “findByAttributes”, “findAllByAttributes”, “deleteByPK”, “deleteAllByAttributes” etc.

Yii 2 can do all of the above purposes but the syntax is much more flexible in that it does not have methods for each purpose but flexible syntax that can be used for flexible purposes.

Also note how in Yii 1 I used array() and in Yii 2 I used []. That is because at the time of Yii 1 array() was the PHP syntax used for creating arrays and at the time of Yii 2 [] could also be used to create arrays. Not really a Yii issue but still the array syntax looks better in the more modern version of PHP.

Use

Due to the Yii 2 framework being written at a time when the version of PHP was later and more modern the Yii 2 framework has made extensive use of the “Use” statement and “Namespaces”. Yii 1 did not make use of these at all probably because they where not implemented in PHP at the time the Yii 1 framework was written.

Nevertheless I feel the “Use” statement and “Namespaces” give the code a more professional feel and it means that the code is only made use of when the code is needed.

I will be updating the blog with more articles on Yii 1 to Yii 2 differences and enhancements as I go a long. I already have plenty of differences lined up but I will be saving them for the next article in this series.

Moving pavements

I had to travel to Manchester a couple of days ago to meet a potential client.

I decided to get the train into Manchester because driving in the city center would have been a nightmare and who knows what the parking is like? equally as terrible no doubt.

I looked up the train journey from my location on Google, it states I need to catch multiple trains and the journey would be 2 hours 30 minutes.

When I actually booked the ticket though it turned out that there was a direct train and the journey takes 1 hour 30 minutes so I am not sure what happened there, maybe Google has not updated the journey for that particular route yet.

Anyways when I arrived at Manchester Piccadilly I came across “moving pavements” …

moving-pavement

The photo above may or may not be Manchester Piccadilly but it shows what “moving pavements” are anyway. Essentially they are like elevators but instead of folding out into stairs they remain flat.

They can either be kept at a straight angle or they can move upwards but they move upwards like a ramp rather than stairs. Anyways I have never seen this before and thought I would share it.

Apparently they are common place at airports but it is not very often I go to the airport. It essentially means people no longer have to walk but can be moved about on the “moving pavements”.

I guess it will come in handy for people with walking difficulties or lots of luggage.

Yii loadModel method?

So it was not long into my Yii development days that I began to notice this awful method that seemed to crop up more and more in other Yii developers code bases.

This is the so called “loadModel” method and it looks something like this …

The idea behind this method is that it is called from other methods in the same controller as itself to return a loaded model for use in the method. I do not understand the point of this method and I never have. I have never used it in any of my Yii 1 or Yii 2 code even though a lot of developers did.

Why is a method needed for loading models?

Please note that this method is only for loading existing models and not creating new ones so the intent behind the method could not have been “It is an easy location to change the model name if I need to so as I do not have to change it in multiple places if ever I need to change it”.

If this had of been the intent then the method would have been written like this …

As I will still need to declare the model separately when creating new models in the controller as the original method did not handle the creation of a new model.

Also a lot of the developers using the “loadModel” method are using different models in their controller anyway which are different from the model loaded in the “loadModel” method, so again the benefits of having the “loadModel” method seem non-existent.

Another so called benefit which could be tried to passed off as genuine is the use of the exception. If the model is not loaded then throw an exception saying the page does not exist.

The test to see whether a user can access the page and the test to see if the record for the model exists based on its ID is normally and best handled in the user permissions / RBAC so it is not needed in the controller.

My conclusion to this is that there is no benefit to using the “loadModel” method and it is more of a gimmick which developers have copied from other developers without thinking about it.

ODesk Readiness Test, I passed!

I took the ODesk readiness test today and I passed. I do not use ODesk to get work but I was just curious as to what work was available so I decided to take the test.

odesk-test

I passed the test perfectly first time in 3 minutes and came 2nd out of 5157998 test candidates. I was so happy with the result that I had to share it.