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.

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.

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.

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.

HTML5 Web Storage Implementation

Recently I have been working on a client project which required the ability to store data from a server on the users local machine. In this case the users local machine was a mobile phone, IOS, Android, Windows etc.

It does not really matter on the platform as it will be stored using the mobile phones web browser and most of the browsers are modern enough to have the new HTML5 Web Storage mechanism.

In actual fact the data will be stored using PhoneGaps implementation of HTML5 Web Storage. PhoneGap is a framework that allows the user to write phone software in HTML5, CSS3 and Javascript.

So for all intents and purposes it is like writing a responsive website that works on mobile phone browsers but is actually compiled and runs like a real native software application. PhoneGap interfaces with HTML5 Web Storage for the purposes of using HTML5 Web Storage mechanism.

So to store the data locally I found WebSQL and HTML5 Web Storage to be my options. Although WebSQL looked perfect for storing and querying the data, it is actually being depreciated and will no longer be in use as a standard in future. So my mind was made up for me in that case.

Web Storage on the other hand seems very straightforward, but this would be the case as it does not include the more complex features of querying the data. Web Storage works by storing name / value pairs. So we can say colour = red, or age = 25, name / value.

Like I said this is straightforward but we cannot say give me all persons over the age of 20 for example there is no querying mechanism.

In actual fact there is no mechanism for even storing multiple persons with ages to begin with. The real structured data is left to the programmer to implement and like wise with querying the structured data.

So what approach did I use?

I decided to store the value of the data as a JSON string and the name would be the table name. So for my project this data needed to be fetched from the web server and stored locally using the Web Storage.

I setup a PHP web server that returned a JSON response upon request via the client. The client did this using JQuery standard Ajax request functions. When I got this JSON response from the server which was basically a dump of a particular database table on the server in JSON format.

I stored it in local storage using the particular database table name for the name value. So in the persons / ages example this would be Person = Encoded JSON string of all data in the server Person table.

So now we have all of data for a particular table from the server stored in local storage. I just repeat this process for all the tables I want to store locally. We now have our data.

But what about querying this data?

Well JQuery does not come, out of the box anyway, with functions for querying JSON data. So a developer might think, I know, I will decode the JSON string and write my own functions for querying this data, possibly by putting the data into foreach loops and returning the records when the data matches the developers expectations. Well that is one way to do it however I am not sure how efficient that would be.

Looping through lots of data just to find single records cannot be very efficient however this is JQuery (Javascript) we are talking about, it is not as if it was designed to do this kind of thing anyway, plus Javascript processing power is becoming more powerful as a whole now in modern day browsers.

It is still not a server side language though and does not query a real database like MySQL which was designed for efficiency, but this is not expected of Javascript anyway.

I do not want to talk about efficiency too much as it is easy to slate querying data this way when a lot of internal libraries might just be doing the same thing under the hood anyway. I cannot imagine there being another way to do it with standard Javascript / JQuery when it comes to the rock bottom.

Anyways enough talk of how querying the decoded JSON data might be handled at a lower level. We as developers have libraries for this kind of thing and luckily someone has written a plugin to do this task anyway called json-sql. Here is the link to the library …

www.trentrichardson.com/jsonsql/

The json-sql library allows the developer to query a JSON string using SQL like syntax. Admittedly it only includes a very small subset of the standard SQL functions but it is most certainly good enough for most purposes, selecting, ordering and where clause. So I used this library to query my JSON data.

So that is pretty much it, the project has a web server which sends JSON responses to the client, data is stored in JSON strings in the client local Web Storage and the data is queried using the json-sql library before being displayed to the user.

This is the way I implemented a server / client, DB synchronized, local storage web software application.

Been using PhoneGap

On one of the latest projects I have been working on the client required that I build a software application that would run natively on multiple phone devices, IOS, Android, Windows and Blackberry.

The client required me to build a native software application for each of these devices because the client wanted to publish the software to the Android and IOS app stores and also because the client wanted the software to be able to run without an internet connection.

Up to yet I have mainly built responsive web applications that can run on a mobile phone through the phones web browser. Due to the client specific requirements this software application could not be done in the same way. If publishing to the app store and running without an internet connection was not a requirement, a web based responsive web application could have still been a viable option.

For previous software applications the responsive web application made sense because those projects where really web based systems that needed the convenience of running through a mobile phone and not a pure phone software application with the specific intent to sell the software as a phone application.

So what is PhoneGap? PhoneGap is a framework that allows developers to construct phone software applications using HTML, CSS and Javascript. After the developer has developed the software application using these languages PhoneGap can then build the phone software to run on multiple phone platforms i.e. IOS, Android plus more.

www.phonegap.com

Obviously this saves tons of time as without PhoneGap or similar frameworks developers would have to construct a software application for each platform. Another advantage of PhoneGap is that it allows web developers to build phone software applications in languages they are use to.

Although PhoneGap has made development easier, one of the drawbacks I have noticed with it is that developers still need to install each SDK. An SDK is a toolkit that allows the compiling of the software application to the phones native device. An SDK has to be installed for each device you want the software application to compile to. Installing each SDK can be a real pain in its own right. Most of the SDKs are installed through the command line and in some cases certain dependencies are required.

Another drawback I have noticed with PhoneGap is that the documentation is not very good. It seems like it is good when you are reading it on the main site or when you are reading it on online tutorials. But then you discover that the documentation you where reading is old and does not work for your version or even that it just simply does not work without you having to do something else which was not mentioned in the documentation. A simple task can look simple when reading the documentation, you do everything the documentation says only to discover it does not work in the way you want it to or even does not work at all.

You must be aware of what type of application you are trying to build and do not try to go beyond its limits when the native coding platform would have been a better choice. PhoneGap seems to be able to do everything the native platforms can do, but in practice it is different or rather you may try to do it but it might have been easier just to code it using the native languages, platforms and tools.

Update: PhoneGap does actually include an online builder which allows you to compile to IOS, Android and Windows without having to install the SDKs locally.

Bootstrap

I have recently been working on client work requiring the use of Bootstrap …

http://twitter.github.com/bootstrap/

Bootstrap is a front-end framework for creating user interfaces, it is developed and maintained by Twitter. Bootstrap also has Yii extension component so it easily integrates with my number one framework back-end choice which is the Yii framework.

http://www.cniska.net/yii-bootstrap/

Before I learned about the Bootstrap framework I was coding the front-end of the frameworks using standard HTML5, CSS3 and JQuery. Now that I have learned about the Bootstrap framework, Bootstrap can do a lot of the work for me that originally I was having to code myself. Bootstrap provides a beautiful set of components such as buttons, menus, grids which essentially I was having to write from scratch before I knew about Bootstrap.

Bootstrap components are also consistent with what many people have come to expect with the web user interfaces that the world is seeing today, clean, streamlined and beautiful.