-
AL MA TE RI Welcome to the MVC World D This book is about CodeIgniter and the world of Model-View-Controller (MVC) web development. Before venturing into the topic of CodeIgniter, it’s helpful to put it into some kind of context. However, most programmers who are new to the world of MVC web development find some of the concepts hard to grasp at first — they’ve been so engrained in the old way of doing things that unlearning is difficult at first.
-
Chapter 1: Welcome to the MVC World In fact, a newbie programmer ’s first PHP page probably looks a lot like this one:
-
Chapter 1: Welcome to the MVC World Six months later, the programmer gets a call from the client, and the problems begin — not big problems at first, but they have a tendency to snowball. The client wants to add a few database fields, change the way the interface looks, and make the application more flexible in certain ways. Out loud, the programmer tells the client that everything is OK, but inside, a sense of low-level panic is brewing.
-
Chapter 1: Welcome to the MVC World }else{ $hp[‘title’] = “Welcome to our web site!”; $hp[‘css’] = “default.css”; $hp[‘bodycopy’] = “This is our web site!”; $hp[‘kw’] = “welcome”; $hp[‘desc’] = “our cool site”; return $hp; } } ?> Now that the data-fetching code is in a separate file, the home page is a bit simplified. You could even say that things are a lot better now:
-
Chapter 1: Welcome to the MVC World extend. Furthermore, MVC frameworks are usually pretty structured, allowing the developer to concentrate on what’s important to the client and the project at hand and not worry about other issues that affect every project (such as security and caching). The point here is not to chastise the programmer or call out deficiencies in his approach. Everyone has been there and done that.
-
Chapter 1: Welcome to the MVC World Because of MVC’s three-part separation, developers can create multiple views and controllers for any given model without forcing changes in the model design. This separation allows for easily maintained, portable, and organized applications that are nothing like anything you’ve worked with before. For example, imagine that most prototypical of early 21st century web applications, the blog.
-
Chapter 1: Welcome to the MVC World ❑ If they want to change the number of blog posts that get retrieved (or even the order in which they are displayed), they update the model. ❑ If they want to change the way the home page looks, they update the view. ❑ If they want to add a new page to their application, they first add a method to their controller and then build out any supporting views (to display content in the browser) and models (to gather data from a database).
-
Chapter 1: Welcome to the MVC World that knew how to render what you wanted to render. For example, if you wanted to draw a rectangle or a circle, you’d subclass an existing class for the appropriate rendering. Controllers, in the Smalltalk world, were originally conceived as being very thin, providing a means of sending messages to the model. This is not a book on Smalltalk, but Smalltalk’s impact on modern computing in general and programming in particular can’t be overstated.
-
Chapter 1: Welcome to the MVC World The next step in MVC (no pun intended) occurred with the arrival of the NeXT operating system and its software. NeXT was a company founded by Steve Jobs in the late 1980s that remained on the market until the early 1990s, when it was purchased by Apple. The NeXT MVC developers found a way to create ever more powerful views and ever more fine-grained Controllers (i.e., one could now track mouse movements and click events).
-
Chapter 1: Welcome to the MVC World Comparing PHP MVC Frameworks When you look at CodeIgniter, Symfony, and CakePHP, you’ll notice quite a few similarities. For example, all three: ❑ Allow you to create models that bind to a data source, views that display content, and controllers that monitor user action and allow updates of models and views. ❑ Use structured folders to separate your application’s components from a central core.
-
Chapter 1: Welcome to the MVC World Figure 1-4 illustrates a typical CakePHP model. Figure 1-4 Symfony’s approach allows you to use either built-in methods or raw queries to access the database abstraction layer. Symfony has several built-in methods to create, retrieve, update, and delete database records. Sometimes, though, it makes more sense to use raw SQL (e.g., you want to return a count on a number column).
-
Chapter 1: Welcome to the MVC World Strictly speaking, CodeIgniter doesn’t require models at all. Although this may seem a bit confusing at first (after all, how is it an MVC framework without the M part?), dropping this requirement gives you a lot of flexibility. For example, it could prove useful if you’re developing applications without a database or XML backend or if you need to prototype something quickly using placeholder data in your controller.
-
Chapter 1: Welcome to the MVC World In the following sections, you see how you’d go about doing that. The examples provided in the next few pages don’t stop long enough to explain how to install and configure CodeIgniter (that’s Chapter 3) or talk about all the advanced features like caching, routing, and the extensive libraries. The assumption is that all that’s been done for you, and that you have a properly working CodeIgniter environment.
-
Chapter 1: Welcome to the MVC World The fetchHomePage() function is very simple, but it pays huge dividends to understand what is going on. Here’s what’s going on in the fetchHomePage() function, step by step: 1. The first line initializes the $data array. You’re not required to do this, but doing so is good practice and is an effective way to avoid unnecessary carping by PHP if you end up returning a null set at the end of the function. 2.
-
Chapter 1: Welcome to the MVC World As before, this controller is bare-bones, consisting of just an initialization function that ties this particular controller to the master class Controller. Once again, notice that with this simple notation, CodeIgniter allows you to extend the basic core classes and create something specific and powerful with very little work. When you’re working with a controller, every function or method maps to an address in your application.
-
Chapter 1: Welcome to the MVC World } function index(){ $this->load->model(‘Page_model’,’’,TRUE); $data[‘content’] = $this->Page_model->fetchHomePage(); $this->load->view(‘home’,$data); } } ?> When you look at this controller, notice how organized it is, and how easy it is to figure out what is going on. Any visitor to the site’s index or home page will kick off a discrete process: Invoke the model, retrieve the data, and display the view with data.
-
Chapter 1: Welcome to the MVC World Notice the use of the $content array whenever you access what you need. You may be wondering about that. Take a look at the model again: if ($q->num_rows() > 0){ $data = $q->row_array(); } When the fetchHomePage() function retrieves the home page content from the pages table, notice the use of row_array(), which converts the results into an array. The keys of that array are the field names, with field values populating the array values.
-
Chapter 1: Welcome to the MVC World user displays data for view loads index() loads controller loads runs fetchHomePage() model Figure 1-5 A Slightly Different Approach: Templates Along with standard PHP templates, CodeIgniter offers a lightweight template parser. To use the parser, all you have to do is load it into your controller and pass in the data from the model. The view would then use pseudo-variables instead of actual PHP variables, thus making your views free of PHP altogether.
-
Chapter 1: Welcome to the MVC World Using Third-Party Templating Systems Most of the time, you’ll want to use PHP templates with CodeIgniter, as it offers the fastest way to both develop and generate views. However, there might be some cases in which you’ll want to use a third-party templating system, such as SMARTY.
-
Chapter 1: Welcome to the MVC World Note the two additions to the index() method: loading the parser library and then calling the parser, passing in as arguments the name of the view and the data retrieved from the model. Also note that the data from the model can be safely stored in the $data array (which has also helpfully been initialized). In the view, you’ll name your pseudo-variables from the keys of this array, which helpfully map to the names of the database table fields.
-
Chapter 1: Welcome to the MVC World ‘live’, ‘type’=> ‘home’); $q = $this->db->getwhere(‘pages’, $options, 1); if ($q->num_rows() > 0){ $row = $q->row(); $data[‘title’] = $row->title; $data[‘css’] = $row->css; $data[‘keywords’] = $row->keywords; $data[‘description’] = $row->description; $data[‘bodycopy’] = nl2br($row->bodycopy); } return $data; $q->free_resul
-
Chapter 1: Welcome to the MVC World Next, use the auto_typography() function in the view:
{title}
If you put five MVC experts in the same room and asked them to tackle this particular problem, you’d probably get at least three different a