Archives For MySQL

Rendering View Files in Yii

February 15, 2011

In the MVC architecture, the Controller reacts to a user request. In doing so, the Controller often loads an instance of a particular Model and then renders a specific View. “Rendering” just means compiling all the pieces together, including static text (HTML and such) and the output from executed PHP code. For example, when a user goes to a page for updating a record, the Controller loads the associated record, and then renders the “update” View, which will display the pre-populated form:

public function actionUpdate($id) {
    $data=$this->loadModel($id);

    $this->render('update',array(
        'model'=>$data
    ));
}

Note: That method would also have code in it for handling the submission of the update form, but I’m trying not to complicate the discussion.

As you can see in that code, the render() method, defined in the CController class, is how a View file is chosen for rendering. The first argument to the method is the View file to be rendered, without its .php extension. The render() method will render the View file within the appropriate layout file. In other words, the View file will be rendered with its context. The above code renders update.php, for the associated Controller, wrapped within the views/layouts/main.php layout file (the default).

The second argument to render() is an array of data that can be sent to the View file. In the above code, the Model instance is being passed along. In update.php, references to the $model variable will refer to the loaded data (note that the View gets its variable names from the indexes used in the array).

The render() method takes an optional third argument, which is a Boolean indicating if the rendered result should be returned to the Controller instead of sent to the Web browser. This would be useful if you wanted to render the page and then send the output in an email or write it to a text file on the server (to act as a cached version).

Sometimes you’ll want to render a View file without incorporating the layout. To do that, invoke renderPartial(). For example, both the update.php and create.php View files, auto-generated by Yii, just provide a context, and then include the form file:

<?php echo $this->renderPartial('_form', array('model'=>$model)); ?>

Since the initial View file will have already be rendered within the layout context, the layout shouldn’t be rendered again. The renderPartial() method will render just the named View file. Its second argument, as with render(), can be used to pass data to the View file. In the above, the Model instance is passed along.

Tip: The renderPartial() method is also used for Ajax calls, where the layout isn’t appropriate.

As mentioned already, the file being rendered comes from the directory associated with the current Controller. For example, when updating an Employee record, the URL is something like www.example.com/index.php/employee/update/id/23. This calls the actionUpdate() method of the EmployeeController class (whose code is partially shown above). That method renders the “update” View, which is to say protected/views/employee/update.php. But there are rare cases where you’ll need to render View files from other subdirectories. For example, you may want to include a search form on a page, with that form found within another View directory. To change the reference point, start the View reference with a double slash, which means to start in the views folder. Then indicate the subdirectory and file, still omitting the extension:

<?php echo $this->renderPartial('//search/_form'); ?>

And that’s all there is to it!

View rendering is one of the most important concepts to grasp in an MVC design. Fortunately, it’s not that hard to follow in Yii. Just remember that if you want your layout file, use render(). If not, use renderPartial(). If you need to pass data to the View file, use the second argument to send along an array, whose indexes will become the names of the variables within the View. Finally, if you need to change the include path, begin with a double slash.

Peachpit Press has just published online an article I wrote titled “Creating a Customer Review System in PHP and MySQL.” The article can be used to expand some of the content in my “Effortless E-Commerce with PHP and MySQL” book.

In this edition…

About This Newsletter

No real theme to this newsletter: a couple of links to interesting things online, recommendations of two blog postings to consider, answers to two recently submitted questions, and some news. I turned a frequently asked question into a “What is Larry Thinking?” topic: how to become a better programmer. I’ll follow up on that topic in a future newsletter, too. Other forthcoming subjects include: starting a new Web site/business, making a career out of programming, and how to organically grow a Web site.

As always, questions, comments, and all feedback are much appreciated. And thanks for your interest in what I have to say and do!

On the Web => Colibri for Windows

As you may know, I primarily use a Mac, so I tend to be less aware of the good stuff available for those of you—okay, the majority of you—on Windows. One Mac product that I used to rely heavily upon is QuickSilver. QuickSilver is an application and document launcher, system navigator, utility, jack-of-all-trades. QuickSilver is free, extendable, and quite excellent. Unfortunately, or fortunately for him, the developer that created QuickSilver was hired by Google to create a somewhat similar product for them called Quick Search Box for Mac. So I have since returned to LaunchBar, with which I’m also quite pleased. But this blip isn’t about good Mac software, this is about Colibri for Windows.

I have no idea where or how, but I recently came across Colibri as a Windows equivalent to QuickSilver. Naturally this caught my attention. And although I haven’t used it myself, I thought it worth mentioning, because if it’s anything like QuickSilver or LaunchBar, some of you Windows power users will really appreciate it. With Colibri, you can control iTunes, interact with Firefox, perform Web searches, launch applications, and more, all from an interface that appears by pressing the right key combination. Oh, and it’s free! One negative from the research I’ve done is that the documentation isn’t great, at least not online. But still, Colibri may be worth considering.

On the Web => “Learning the Yii Framework” Series in French!

Nico, from Mémorandom, recently contacted me about translating my popular Learning the Yii Framework into French and publishing it on that site. I’m pleased to say that the first five parts of the series have already been translated and are available online:

The posted translation should hopefully help expand Yii’s international influence. My thanks to Nico for the nice words on my series and for the work in translating it!

On the Blog => Creating Forms with the Yii Framework

HTML forms are one of the key pieces of any Web site, providing an easy way to get data from the user. But, as is the case with many things, creating forms while using a framework such as Yii is significantly different than creating forms using standard HTML alone. In a recent post, I covered what you need to know to get started creating HTML forms when using the Yii framework.

On the Blog => Markdown and MultiMarkdown

In previous newsletters I’ve made reference to Markdown and MultiMarkdown, two of my favorite new technologies (well, new to me). The one is an extension of the other and both allow you to write more naturally, without concern for formatting, and then output that text in HTML and other formats. I’ve been using Markdown for my newsletter for a couple of months now and plan on using MultiMarkdown when I begin self-publishing books this year.
You can read a quick introduction to both technologies, and see where to head for more information, in this blog post.

Q&A => What happened to Ruby on Rails?

Jason sent me this question, pointing out that “It was all the rage a while back”. True, true. So what did happen?

First, I’ll say that I adore Ruby. It’s a beautiful language, odd as that may sound. If I need to create non-graphical utilities or scripts to be executed via a command line, Ruby is my language of choice. Ruby has great power yet simplicity, and is more object-oriented than most (e.g., any number in Ruby is itself an object). And Rails is a great framework for doing Web development. It does a lot of the work for you and has outstanding features. In fact, Rails recently came out with version 3, which was a major revamping, integrating features that cropped up in Ruby-based alternatives to the Rails framework.

Anyway, I suspect part of the reason that Rails doesn’t get the attention it once did is that it’s no longer “new”. Secondarily, I think the impression of Rails was severely damaged by what happened with Twitter. Twitter was originally written using Ruby on Rails but Twitter got to a point where the site wasn’t able to handle its demand. Rightly or not (probably some of both), Ruby on Rails took the brunt of the bad press for the outages. I would argue that one can’t use Twitter as a reasonable benchmark, though, as very few—perhaps only a handful—of sites have the same level of activity as Twitter. I suspect that most sites would crash if they started seeing that kind of demand. Poor scalability is not a problem of Ruby on Rails. In fact, honestly, I don’t know that any technology has inherently poor scalability, but that all technologies will degrade under high loads, if not optimized for demanding conditions.

To be fair, performance is a concern whenever you use a framework. Framework-based applications, by definition, are going to be more bloated and slower than non-framework applications. That’s just the way it is and will be. In turn, one gets much faster development with a framework. In any case, I know Twitter eventually replaced their Ruby on Rails code with something else (written in Scala, I believe), but Groupon and Hulu use Ruby on Rails, and these are also very demanding sites.

Finally, as for myself, despite my affection for Ruby and Ruby on Rails, the reason I don’t regularly use RoR for Web sites is because there’s now a good, comparable PHP framework (for me, that’s Yii). I had been programming with PHP for several years before learning Ruby and Rails. When I came across RoR, there was no PHP framework like it. But I’ve since found, and grown quite fond of, Yii, so my need for a quick development Web framework has been met, allowing me to use PHP, the language that I’m still most comfortable with.

Q&A => What is the Benefit of the Model in MVC?

The MVC design pattern, short for “Model, View, Controller”, has become an extremely common way to write software and is used by most, if not all, major frameworks. But the MVC approach is not necessarily intuitive and can be confusing, or simply hard to properly implement, for beginners. Brett, for example, sent in this very reasonable question:

“Views and Controllers make sense to me, but have a Model to pull out data and then to have a
View call it, doesn’t seem to flow that well in my head. What are the benefits of using Models?”

In case you’re not familiar with MVC, the View is what the user sees and interacts with. On a Web site, this means HTML, with a dab of PHP embedded as necessary (e.g., to echo the value of a given variable). The Model represents a set of data. Often a Model corresponds to a particular database table, with an instance of the Model representing a particular row from that table. Models can also represent data sets not being permanently stored, such as the contents of a contact form, which get emailed instead. The Controller is the agent between the View and the Model. The Controller responds to user actions, such as requesting a specific page (in which case the Controller loads any necessary Model and then renders the proper View) or handling a form submission (in which case the Controller may create a new instance of a Model based upon the submitted data, then save the Model, and then render a different View). An important aspect of MVC is that Controllers should actually be lightweight, in terms of code. The applicable adage is “thin Controllers, fat Models.” The most common design error by beginning MVC-ers (?) is to put too much logic and functionality into the Controller, instead of in the Model where it belongs. But why?

Let’s quickly think about the Controller. The Controller responds to user actions and quite frequently then loads an instance of a Model which the Controller then passes to the View. Much of the Controller logic is not really particular to a given application, but rather slight variations on common themes. With a site for managing employees, the Controller’s actions would entail: listing all employees, viewing a particular employee, searching for employees, adding a new employee, updating an existing employee, and deleting a particular employee. Now say the site is for managing an inventory of products (like on an e-commerce site). In that case, the Controller’s actions include: listing all products, viewing a particular product, searching for products, adding new products, updating existing products, and deleting existing products, among others. As you can see, there’s a lot of repetition here, the only difference being the swap of “employee” for “product”. This is to say, the only difference is the Model itself. And that’s why the Model is so critical: because it is the heart of an application. When you’re deciding what a site is about, and when you’re designing the database, you’re dealing with the Model. The same Model will be used by many different Controller actions and View files. So let’s look at the Model in detail…

The Model represents the data, but what does that mean? It means, for one, that a Model defines the properties for an object, like a “user” object has a first name, last name, email address, password, etc. The Model also defines the validation routines that any data set must pass: the email address must be a valid email address, the user level must be an integer, the date entered value is the current moment upon insert, etc. Whether a new Model is being created or an existing Model is being updated, the same validation rules will apply.

Models also sometimes have custom functions for returning formatted properties. Models shouldn’t output HTML, but a user Model might have a function that returns the user’s name in the format Last Name, First Name MI.. Or a user Model might have a “member since” function that returns the user’s registration date in a particular format (not the database timestamp). By putting this functionality in the Model, any View can make use of it. If that functionality were defined in a Controller or View, then only that Controller or View could benefit.

Just as the majority of Controller code may be the same from site to site, some of the Models can be exactly the same from one site to another, or just slightly different. If you’ve created a user Model that does everything you need it to do, it’s likely that the same Model can be used on multiple sites (this, of course, is a benefit of object-oriented programming in general). With the MVC architecture, the biggest differences from one project to the next are therefore the Models you define and the corresponding Views.

Coincidentally, the Yii framework’s site just posted a nice article titled Best MVC Practices, which you may benefit from reading, whether you use Yii or not.

What is Larry Thinking => Becoming a Better Programmer

How one becomes a good programmer is one of the most common questions I see, especially from those just getting started. A reader purchases one of my books because they want to learn X, and then they want to know how long before they’re an expert programmer. The answer to that particular question—how long—is short and sweet: I have no idea. It really depends upon who you are, what you already know, how you learn, and so forth. But many people, when they ask you a question, don’t care for the “I have no idea” answer, even if, or especially, if that’s the correct answer. So rather than answer that question, I thought I’d take a moment to discuss the more appropriate question of “How do I become a better programmer?” The key is “better” as opposed to “good,” “expert,” “master,” and the like.

Perhaps it’s merely semantics, but one shouldn’t aspire to be a good programmer, but rather a better programmer. Like, well, almost every job, a programmer does not have a fixed end that one gets to. I’ve been programming actively for going on 12 years now and, whether I’m currently a good programmer or not, my hope is that next month I’ll be a better programmer than I am today. So how do I, or anyone, work towards being a better programmer?

Read. Do. Review.

Pithy things are easier to remember and just sound more true, so I’ve assembled all my thoughts into those three words: Read. Do. Review.

Read.

There are plenty of tasks you can pull off without reading a thing, such as changing a tire or unclogging a sink, but you can’t learn to program without reading something: a book, a manual, articles, whatever. Programming simply does not allow for blind guesses. Now clearly, my books are the best way to learn anything and should always be your first stop on a new path. This cannot be denied. (I really am joking.) But even after reading all of my books multiple times over, there’s probably a benefit of reading other writers’ books (blasphemy), to get a different perspective. Assuming you’re a book-reader type, that is.

Books do three things well. First, they can teach beginners effectively. Second, they can show how to apply knowledge. Third, they provide a cohesive body of information. I’m a book person and a book writer, so I’m completely biased, but I think that reading books about programming is always for the best. I still read books by other writers, even if they’re on the same subject and targeting the same audience as some of my books. Always good to see what others are thinking!

I mention manuals second for three reasons. First, not all programming languages or technologies have actual manuals, let alone good ones (the PHP manual is pretty good, in my opinion). Second, manuals tend to promote syntax and functionality above real-world implementation. Third, manuals tend to be written by committee, thereby lacking cohesion. On the other hand, in theory, manuals will always be the most up to date of the available options.

Articles are a great way to learn new tricks, of course. You might think this means reading an article on a specific subject only if you want to learn about that subject, but you might get some value by seeing tangential code. For example, say an article is on creating an RSS feed using PHP and MySQL. You might not need to do this, but in reading the article, you could learn something about PHP and MySQL, about XML, and so forth. And again, you’d get a different writer’s perspective and approach.

Do.

The second step is to simple: program. You can’t really learn or improve without doing. If you don’t have actual programming work to do, then come up with your own idea and implement it. In a way, programmers, Web developers, and the like are quite fortunate, as they can practice, learn new things, create functional projects, etc., without spending a dime (or without spending much money). Many other professions, such as architects, don’t have that luxury. So take advantage of that freedom!

Review.

I suspect most programmers focus on the “doing” and spend very little time on the “reviewing,” which I believe is probably more important in the long run. I don’t mean testing, which is necessary, too, but actual code reviews. Are the comments still thorough and accurate? Does the code make assumptions? Are errors handled gracefully? Is the code properly formatted? Is it consistent in terms of formatting, syntax, variable names, and the like? Most programmers, in time, can make things work. It’s these other points that differentiate the average programmer from a better one. But don’t stop after reviewing your code…

You should review other people’s code. See what they did. Does it make sense? Does it adhere to the same principles just outlined? What does that code do differently than the code you’d write? Is one approach better? If so, why? I’ve become a better programmer (and a better writer) by providing support in my forums. In looking at what other people did, and helping them solve problems, I’ve learned a ton. And I know that the handful of other people that are kind enough to donate their time to assist feel this way as well (and my unending gratitude to them).

A key learning tool when reviewing code is explaining what code does. There’s a related debugging approach called rubber duck debugging that’s similar to what I’m suggesting here. One level of programming knowledge is getting something to work. A higher level is understanding why it works. An even higher level is being able to explain why it works. I know I’ve become a better programmer by writing books, although that’s a pretty steep and unreasonable step for many to take! A few times, though, as I write a book I’m explaining why I used such and such code, and in the process of explaining, I realized that the approach could be improved. You don’t actually have to write a book or sit someone down, but go through code some time and try to explain why it’s doing what it’s doing. You’ll learn a lot.

And…

In a subsequent newsletter, I’ll write a bit about what general and specific skills are critical to being a better programmer, but I wanted to just focus on the process of improving here. What did I omit? Formal training and certification. Formal training, be it a school course or not, is a great way to become a better programmer, which I think goes without saying. Or it should be a great way, as not all classes or teachers are alike (true for books, as well). As for certifications, I understand they can help you get a job, but I don’t put much faith in passing a certification test as a way of becoming a better programmer. You can certainly learn some technicalities that way, but I doubt you’ll learn that much in terms of real-world knowledge and the ability to apply information.

Larry Ullman’s Book News => “PHP for the Web”, “PHP and MySQL for Dynamic Web Sites”, and More!

As mentioned in my previous two newsletters, I’ve been writing some articles and blog posts for Peachpit Press’s Web site, all supporting my Effortless E-Commerce with PHP and MySQL book. I’ll post links to them on my Web site, and in future newsletters, as they go live.

I’ve wrapped the first draft of the the fourth edition of “PHP for the Web: Visual QuickStart Guide” and am almost through with the rewrites. Along with fixing any minor problems, updating the code for the latest version of PHP, and adding a “Review and Pursue” section to the end of each chapter, I’ve been able to add a new chapter. That chapter will replace the original Chapter 13, “Regular Expressions,” as the ereg() function has been deprecated in PHP 5.3. The new chapter is called “Putting It All Together” and will show how to use everything covered in the book to assemble a mini-Web application, with authentication and full CRUD (Create, Retrieve, Update, and Delete) functionality. The chapter is similar to the three popular example chapters in my “PHP and MySQL for Dynamic Web Sites: Visual QuickPro Guide” book, although using a different example.

In February, I start writing the fourth edition of my “PHP and MySQL for Dynamic Web Sites: Visual QuickPro Guide.” It will also have a “Review and Pursue” section added to the end of each chapter. I’m also going to clean it up a bit, and remove references to PHP 6, which, in the time from when I started writing the third edition to started writing the fourth edition, went from about 50% complete to limbo to non-existent. So that’s the last time I’m going to try to be that far out ahead of the curve.

I am also planning on working on my self-published JavaScript book starting in February as well. I’ll try to dedicate some time to it and, as I’m publishing it myself and writing it using MulitMarkdown, I’ll be able to post free, HTML sections from the book online as I go. Thanks to everyone for their continued support and interest on this new book!

Yii 1.1.6 Released

January 25, 2011

Version 1.1.6 of the Yii framework was released a few days ago. Along with bug fixes, 1.1.6 includes a couple of new features, most notably database migration and a new Query Builder. Database migration is a feature that comes from Ruby on Rails (well, that’s where I first heard of it) and it allows for better version control. Basically database migration allows you to associate database changes with versions, so that you can better sync updates to the PHP code and the underlying database. It’s a useful tool for projects being developed by a team or in stages.

The new Query Builder is an object-oriented way to create custom SQL statements. This isn’t really a new feature (in the sense of allowing you to do something you couldn’t do before) but lets you do something you might commonly do but in a different way. See the above link for a thorough discussion and demonstration.

For some reason, the 1.1.6 release of Yii includes an article on Best MVC Practices. This isn’t really part of the framework itself, but is a useful read for anyone using Yii or other MVC approaches.

Mémorandom, which is translating my popular “Learning the Yii Framework” into French and publishing it online, has recently posted the translated versions of two more parts in the series. The fourth part is Defining Databases for the Yii Application. The fifth part is Creating Models, Views, and Controllers in Yii. My thanks again to Nico for the nice words on my series and for the work in translating it!