Yii Part 1


I recently started developing my first application using the PHP framework Yii.   I intend this series of articles, not to be a tutorial (there is already a great series from Larry Ullman) but more a blog of what problems I encountered, both technical and Architectural.

I’m hoping that this series will help you to fill in the same gaps as I found when first starting to use Yii.  please do add any areas that you think I’ve missed in comments below.

Before You Start !!!

One of the fundemtal considerations that is completely missed in all the introductions is the fact that you are probably really looking to build two applications and not one.  That is, a user frontend and an admin backend. If you are, then from a security aspect, you will want to somehow separate these two parts.

I am surprised that this is not already catered for in the basic application created by Gii or within the default controller structures.

The first solution that I liked (remember that I am still a realtive beginner), I found on the Yii forums by a user called “mindplay”.  You can find the original article here but I will summarise it and add my own slant as follows.

Separation of Admin Controllers

By following a naming convention for admin and public controllers, we end up with controller names like these:

  • UserController
  • UserAdminController
  • PageController
  • PageAdminController
  • etc.

Now for the clever bit. Rather than adding a route for each of the admin controllers, we simply do this:

 PHP |  copy code |? 
1
'urlManager'=>array(

 PHP |  copy code |? 
1
 'urlFormat'=>'path',     // use "path" format, e.g. "post/show?id=4" rather than "r=post/show&id=4"

 PHP |  copy code |? 
1
 'showScriptName'=>false, // do not show "index.php" in URLs

 PHP |  copy code |? 
1
 'appendParams' => false, // do not append parameters as name/value pairs (DO NOT CHANGE THIS)

 PHP |  copy code |? 
1
 'rules'=>array(

 PHP |  copy code |? 
1
 'admin/<controller:w+>'=>'<controller>Admin/index',

 PHP |  copy code |? 
1
 'admin/<controller:w+>/<id:d+>'=>'<controller>Admin/view',

 PHP |  copy code |? 
1
 'admin/<controller:w+>/<id:d+>/<action:w+>'=>'<controller>Admin/<action>',

 PHP |  copy code |? 
1
 'admin/<controller:w+>/<action:w+>'=>'<controller>Admin/<action>',

 PHP |  copy code |? 
1
 '<controller:w+>'=>'<controller>/index',

 PHP |  copy code |? 
1
 '<controller:w+>/<id:d+>'=>'<controller>/view',

 PHP |  copy code |? 
1
 '<controller:w+>/<id:d+>/<action:w+>'=>'<controller>/<action>',

 PHP |  copy code |? 
1
 '<controller:w+>/<action:w+>'=>'<controller>/<action>',

 PHP |  copy code |? 
1
 ),

The biggest down fall of this method that I have found so far, is that you still need to defines separate views within the default controller actions. So that your IndexAdmin action needs to point to a different view to your Index action.



If you found this article useful » please +1 me on Google.