specializing in digital media technologies

Digital Media and Communications Insights, Inc.


Larry Ullman's Blog

Basic Controller Edits in Yii

This entry is part 8 of 8 in the series Learning the Yii Framework

After using Yii‘s command-line tools to build an application’s base structure, and then to create its Models and crud functionality, there’s still quite a bit of customizing to do (although Yii really does perform the bulk of the work). Previous posts discuss some of the common changes one makes to Models and Views at this point in the development stage; here I’ll discuss Controllers. I have personally found that I don’t make nearly the level of alterations to my auto-generated Controllers as I do to my Models and Views. This makes sense, as the Model should have the bulk of the code, the View is the interface the end user sees, and the Controller is largely an agent between the two (see my series on the MVC architecture for more on this).


Edit for Yii 1.1: The $defaultAction line is no longer present. Also, the names of some of two of the action methods have changed to match the new names of the corresponding View files: actionView() and actionIndex().


The first thing you’ll encounter within a Controller class is a constant called PAGE_SIZE:

class EmployeeController extends CController
{
    const PAGE_SIZE=10;

This constant represents how many records should be display per page, applying to the list and admin Views for that Controller. Change this to whatever value you want and Yii will automatically paginate the records on those pages thanks to this code (from a list.php View file):

<?php $this->widget('CLinkPager',array('pages'=>$pages)); ?>

Just after that, your Controller will have a line like this:

public $defaultAction='list';

Remember that Controllers are the actions one takes, listing information, showing particular records, handling form submissions, and so forth. For each action there is a corresponding method in the Controller class: actionList(), actionShow(), actionCreate(), etc. The above line dictates which method is called if not otherwise specified. So with that line, the URL www.example.com/index.php/employee calls the actionList() method whereas www.example.com/index.php/employee/create calls actionCreate().

Your Controllers should also have several non-action methods, including accessRules(). This method is a key part of the security picture, dictating who can do what. For the “what” options, you have your actions: list, show, create, update, and delete. Your “who” depends upon the situation, but to start there’s at least logged-in and not logged-in users, represented by * (anyone) and @ (logged-in users), accordingly. Depending upon the login system in place, you may also have levels of users, like admins. So the accessRules() method uses all this information and returns an array of values. The values are also arrays, indicating permissions (allow or deny), actions, and users:

public function accessRules()
{
    return array(
        array('allow',  // allow all users to perform 'list' and 'show' actions
            'actions'=>array('list','show'),
            'users'=>array('*'),
        ),
        array('allow', // allow authenticated user to perform 'create' and 'update' actions
            'actions'=>array('create','update'),
            'users'=>array('@'),
        ),
        array('allow', // allow admin user to perform 'admin' and 'delete' actions
            'actions'=>array('admin','delete'),
            'users'=>array('admin'),
        ),
        array('deny',  // deny all users
            'users'=>array('*'),
        ),
    );
}

That’s the default setting, where anyone can perform list and show actions, meaning that anyone can list all records or show individual records in the associated Model. The next section allows any logged-in user to perform create and update actions. Next, only administrators can perform admin and delete actions. Finally, a global deny for all users is added, to cover any situation that wasn’t explicitly defined. This is just a good security practice. Note that these rules just apply to this Controller; each Controller needs its own rules.

You’ll want to customize the rules to each Controller and situation. For example, I did a site with a subscription system, represented by a Contact Model. In that case, anyone had to be allowed to create new Contact records but only the admin was allowed to list or show Contact records. Generally, though, I think most Controllers would allow everyone to perform show and list actions.

You can also create more sophisticated conditionals to create permissions, but that will be a subject for another post. For example, on one project I did, any logged-in user could create certain types of content but they could only update and delete records that they themselves created. Or you could allow users show permission only on their own Contact record.

Finally, you may need to change your Controllers so that the retrieval of Model records is handled differently. There are a few methods that load records to be used in a View. Some of the methods, like actionShow() and actionUpdate(), call a loadModelName() method whose job it is to retrieve a single record. This method’s name will differ from Controller to Controller—loadEmployee() or loadDepartment()—but it’s always used to retrieve and return just a single record. Other methods, like actionList() and actionAdmin() retrieve every Model record. In these methods, there are a couple of changes you may want to make. For starters, if the Model in question is related to another Model, as defined in the Model class’s relations() method (see my post on Models), you can invoke that relations when you retrieve the record(s). For example, this code will retrieve every department, plus the department head’s employee record for that department:

$models=Department::model()->with('employees')->findAll();

You only want to do this if you’ll use the related records, of course, like if the page that lists every department also lists the department head or if the page that shows an employee’s record also indicated what department they are in.

You might also tweak the criteria applied to these methods, but that is a big topic. It basically involves adding WHERE SQL conditions to a query. I’ll address it in another post but you can also see the Yii documentation, of course.

So this makes the eighth post in a series on using the Yii framework, from start to kinda-finish. I’ve got a bunch of miscellaneous topics on the subject to post about, but I won’t write those up formally as part of this series. To find those, or any other posting on Yii, use the tags at right.

As always, thanks for reading and let me know if you have any comments or questions.

Larry

Series Navigation«Basic View Edits in Yii
Filed under: MySQL,PHP,Web Development — Tags: , ,

53 Comments »

  1. I was able to finish my first YII web application within a short time thanks to this tutorial.

    Thanks Larry.

    Comment by Chamal — November 23, 2009 @ 5:04 am

  2. I’m glad to hear that. Congrats! Let me know if there’s anything in particular you’d like me to write about (I have a few Yii-specific topics lined up for December).

    Comment by Larry — November 23, 2009 @ 9:48 pm

  3. Very nice tutorial! Thank you!

    Comment by Vic — November 27, 2009 @ 4:38 pm

  4. You’re quite welcome. Thanks for the nice words and let me know if there’s anything specific you’d like me to write about.

    Comment by Larry — November 27, 2009 @ 5:59 pm

  5. Your tutorial is great and simple. Put me up and running with the basics of yii in no time. I would like to know if you plan to do a I18N tut?

    Thanks!

    Comment by Jimmy Armand — December 1, 2009 @ 2:48 pm

  6. Thanks for the nice words. I appreciate it! As for l18N, I’ll consider that. I’m writing one on FCKEditor and Yii now, and will be doing one on Zend_Lucene (search engine) and Yii soon.

    Comment by Larry — December 1, 2009 @ 3:54 pm

  7. Very well put together tutorial, thanks for the hard work.

    A co-developer and I are just starting to explore Yii for an upcoming project, and this series was a great lead in for me :)

    Comment by Dave — December 3, 2009 @ 11:22 am

  8. Thanks for the nice words. I’m glad it’s been helpful. Let me know if there’s anything specific you’d like me to write about.

    Comment by Larry — December 3, 2009 @ 11:51 am

  9. Larry, I think it’d be usefull for me and probably others to see an example of creating a search form with all it’s controllers, safe sql queries to db and probably something else related to search in your future tutorials (not Lucene, but some kind of a simple search). Thanks again for your articles!

    Comment by Vic — December 7, 2009 @ 6:07 am

  10. Thanks for your suggestions, Vic. I’ll see what I can do!

    Comment by Larry — December 7, 2009 @ 11:04 am

  11. I’m new to yii and where this code $models=Department::model()->with(‘employees’)->findAll();

    could be placed to show department name when listing employees?

    Comment by Yii newbie — December 26, 2009 @ 12:39 pm

  12. Well, that’s the code for retrieving every department and employee, and it would go in the Controller, like in the actionList() method. The code for actually showing the department name would be in the View. In the list View, you would have a foreach loop going through the $models array, assigning each to $model. Then you could print out $model->name, which would be the department name.

    Comment by Larry — December 26, 2009 @ 2:47 pm

  13. Thanks this blog really help me lot to understand framework basics. Will move for next tutorial now… thank you…

    Comment by Sunny Chevli — January 1, 2010 @ 3:06 am

  14. Thanks for the nice words. Much appreciated!

    Comment by Larry — January 3, 2010 @ 9:33 am

  15. Thanks for taking the time to write up this quality series. You’ve helped to get me up to speed very quickly, and Yii is now my favourite PHP framework too.

    Comment by Sherri — January 17, 2010 @ 12:04 am

  16. Thanks for the nice words. I’m glad the posts have been helpful and that you now like Yii, too!

    Comment by Larry — January 19, 2010 @ 11:23 am

  17. Excellent tutorial. Thank you! I was up and limping within a couple of hours.

    Comment by queej — February 4, 2010 @ 4:58 pm

  18. You’re quite welcome. Thanks for the nice words.

    Comment by Larry — February 6, 2010 @ 12:21 pm

  19. 这个教程确实很新,看来要好好学习一下yii,谢了
    (Roughly translates to “This course is truly very new, looks like must study well yii, thanked” according to Yahoo! Babel Fish).

    Comment by lin — February 7, 2010 @ 9:09 am

  20. You’re welcome!

    Comment by Larry — February 8, 2010 @ 6:38 pm

  21. Larry is there a screencast or video-tutorial about yii? I liked this one very much, and I understand everything but if I wanted to do a totally different webpage I wouldn’t know how to do it. What do you recommend me in order to enlarge my knowledge about this framework? Thank you!

    Comment by Sebastian Breit — February 17, 2010 @ 7:29 pm

  22. Thanks for the nice words. On the Yii framework’s docs page, there’s a link to a screencast. Other than that, I would recommend the blog tutorial (also part of the Yii documentation), which walks through creating a reasonably-sophisticated application using Yii.

    Comment by Larry — February 18, 2010 @ 9:04 am

  23. Dear Larry,

    Thanks.. thank you very much….
    Its an excellent tutorial on Yii…

    Regards,
    Rejeesh

    Comment by Rejeesh — February 26, 2010 @ 12:41 am

  24. Thank you for the nice words. Much appreciated.

    Comment by Larry — February 26, 2010 @ 5:29 pm

  25. Great tutorial.
    Thank you very much.

    Comment by Mihai — March 17, 2010 @ 9:22 am

  26. You’re welcome. Thanks for saying so.

    Comment by Larry — March 17, 2010 @ 12:05 pm

  27. Here is my problem. I got code, theme, the works. It works! Why and how would I integrate that into yii? What do I get, that I don’t have now?

    OK, simpler question. I got a bunch of classes. Where do I put them in yii?

    Most people I talked to about this said I don’t need a framework. If so, who does?

    In other words, what’s it in it for me?

    I never understood agility.

    Comment by chris — March 19, 2010 @ 8:09 pm

  28. I’m not into convincing people of things, especially those that don’t want to be convinced. From what it sounds like, you’ve got a system that works for you, so you’ve got no need to use a framework. Who does? Well, people that don’t have an established system already, for one. And people interested in learning new things and seeing if there’s not a better way out there, for two. When we stop learning, we shut down progress.

    Comment by Larry — March 20, 2010 @ 8:13 am

  29. Thank you very much for writing this tutorial. It has been a great introduction to yii programming.

    Comment by Blacloud — April 7, 2010 @ 8:45 am

  30. You’re quite welcome. Thanks for the feedback!

    Comment by Larry — April 7, 2010 @ 9:11 am

  31. I have a plan to use yii framework for one of my project.

    Thanks for this great informations.

    Comment by Taner Ozdas — April 10, 2010 @ 1:40 am

  32. You’re quite welcome. Thanks for the nice words and good luck with your project.

    Comment by Larry — April 13, 2010 @ 9:52 am

  33. Thanks for the this great tutorial!

    I’m starting in the PHP and Yii development and your posts guided me through the first steps.

    Comment by André Luiz Müller — April 20, 2010 @ 2:52 pm

  34. Thanks for the nice words and for the feedback. I’m glad it was useful. Good luck with your Yii projects!

    Comment by Larry — April 24, 2010 @ 10:01 pm

  35. You have made a fine tutorial. The one thing that I don’t see is how I should add links to the main page, that might appear if an admin logs in that I could have appear where I could edit the employees and department table. Oh my first guess is it would be simple for me to drop in some links in the first page and some function like isAdmin to tell the page to display these links, but like so many other times I end up guessing I usually guess wrong. This MVC is too new for me to trust my guesses. Could I get a hint or two about how I should go about this. Sign me, need to be hit by a clue by four. thanks!

    Comment by Garry Freemyer — May 1, 2010 @ 5:21 pm

  36. Thanks, Garry. Two ways of handling this: first, show or don’t show a login link. I normally don’t if only an admin would login (don’t want to confuse others); instead I just have the admin bookmark the login URL. Then this is something I put in my views/layouts/main.php script:
    widget('UserMenu',array('visible'=>(!Yii::app()->user->isGuest))); ?>
    That says to show the UserMenu widget should the user not be a guest (i.e., be logged in). The UserMenu widget would then show admin-specific links. That’s pre-Yii 1.1 code, so I forget offhand if it’d be slightly different in Yii 1.1 or later.

    Comment by Larry — May 1, 2010 @ 5:59 pm

  37. Larry, thank you :-)

    Comment by Winston — June 7, 2010 @ 11:21 am

  38. You are most welcome!

    Comment by Larry — June 8, 2010 @ 10:51 am

  39. It’s a dear experience to learn Yii from your tutorials [and comments!]. ..
    Didn’t make it with the ‘foreach’ you suggested to show department’s name instead of its id. Should I try it in which View? index, view or _view? (I’m using Yii 1.1)

    Again, thank you very much for this.

    [I wish I could properly translate(pt-BR) a few lines from this Yii series and share it with my peps, you mind?]

    Comment by Cynthia — June 8, 2010 @ 11:06 pm

  40. Thank you very much for the nice words and do feel free to translate this so long as you give me credit, of course. You could also reference my books, if you’d like (I’ve written several on PHP, Web development, et al.) I’m glad you feel the content is worth sharing.

    The foreach you’re referring to, I think, is on the basic View edits page. It goes in the Departments.php Model file.

    Comment by Larry — June 10, 2010 @ 8:36 pm

  41. Superb article on Yii startup. Good tutorial for beginners and ZCEs(myself) alike.

    Comment by Senguttuvan G — June 12, 2010 @ 11:32 pm

  42. Thanks for the nice words! You’re a Zend Certified Engineer? What are your initial thoughts on Yii compared with the Zend Framework?

    Comment by Larry — June 13, 2010 @ 12:24 pm

  43. Very useful tutorials to understand the basics of this framework, which we are just starting to use. But here’s the thing, I am not doing the YII and php and database stuff, I am just responsible for tweaking the css that controls the look and feel.

    I see that there are several copies of styles.css (in our case for detailview, listview and gridview. There are single copies of form.css, main.css, pager.css.

    I’d love a tutorial (or pointer to one) that explains how to manage the css for a YII project. Thanks.

    Comment by Richard Viets — June 17, 2010 @ 9:27 am

  44. Thanks for your post. I don’t know of any tutorial on this particular subject but I find the CSS files pretty apparent to use (they’re well documented). Also, in my experience, normally designers use a new HTML design with its own CSS files, making those Yii-created CSS files irrelevant.

    Comment by Larry — June 20, 2010 @ 4:50 pm

  45. Sir…
    i am beginner with YII.
    i want to display record with different two tables.
    display employee..
    CHtml::encode($data->departmentId);
    insted of departmentid i want to write name(from table department)
    -BhavikChauhan

    Comment by Bhavik Chauhan — June 21, 2010 @ 7:15 am

  46. No problem. You just need to identify the relationship between the two in the two Model definitions, then select the employees with the departments in your Controller.

    Comment by Larry — June 22, 2010 @ 7:34 pm

  47. thanks for reply,,
    your language is so easy..
    really useful blog..
    plz give me some more hint abt “identify the relationship”and “select the employees with the departments”..

    Comment by Bhavik Chauhan — June 30, 2010 @ 4:07 am

  48. Thanks for the nice words. Could you please clarify what your questions are?

    Comment by Larry — July 1, 2010 @ 7:15 am

  49. I Have done…
    thank you very much.

    Comment by Bhavik Chauhan — July 1, 2010 @ 7:32 am

  50. Hi,

    Thanks for the nice tutorial! It really helped me in starting with Yii!

    Comment by Pastia — July 6, 2010 @ 4:26 am

  51. You’re welcome. Thanks for the feedback!

    Comment by Larry — July 6, 2010 @ 9:06 am

  52. Dear Larry,
    I have been following all ur 8 posts.

    & a big thank u.
    After reading some documentation(Yii definitive guide), I was trying to understand how all the pieces work together. But, it seemed to me as complex.

    But, ur tutorial was a big help for me.

    once again, thank u.

    Comment by Sudip — July 10, 2010 @ 7:02 pm

  53. Thank you very much. Very nice of you to say. Good luck with your Yii work!

    Comment by Larry — July 12, 2010 @ 8:03 am

RSS feed for comments on this post. TrackBack URL

Leave a comment




If you have a question, are seeking information, want to download files, or generally have any need related to a specific book, please make sure you are using the correct link. Check both the title and the edition.