MintyPHP Tutorial

Reviews
Shared by: techmaster
Stats
views:
4
rating:
not rated
reviews:
0
posted:
10/28/2008
language:
pages:
0
MintyPHP Tutorial Introduction This tutorial will introduce you to the ease of use of MintyPHP, its components, and the MVC (Model-View-Controller) design pattern, if you are not already familiar with it. In this tutorial we will develop a blog-like web site to show the relationship between objects. What is MintyPHP? It is NOT a full featured framework. Instead it is a collection of classes which help a developer adhere to the MVC pattern while speeding up development. MintyPHP uses other technologies which you may already be familiar with such as the Smarty template engine and the Prototype and Scriptaculous JavaScript libraries. With that said, there are three key components to MintyPHP. These are directly related to their MVC counterparts. Model (/app/model/Model.php) This class provides access to your data. There is a one to one relationship between a class that extends Model and a table in your database. Instantiating a class that extends Model will automatically populate the fields in your object, instantiate any children, allow for creating new records, and updating all without writing a single line of SQL. Controller (/app/controller/Controller.php) The Controller class handles the rendering of the page using the Smarty template system. The PageController class extends Controller and handles any requests for static content automatically. This is done in conjunction with the router.php and ajax.php files. We will get into more detail later. Views (/app/view/pages) You will write your markup in template files that have the .tpl extension. Dynamic data can be inserted into these templates using the Smarty curly brace syntax. A main template (/app/view/template/template.tpl) should be created which contains any markup that is consistent across the site such as header, footer, and navigation. Naming Rules 1. 2. 3. 4. All classes that extend Model must be contained in a single file. A Model's class name and file name must begin with a capital letter. The above also applies to class which extend Controller. Controller names must be camel case and end with Controller. For example, the UserController? class must be in a file called UserController?.php. 5. A table associated with a model must be a plural of the model name. The "User" model will have a table called "users". This also applies to models that already end in the letter s. The Business model would have a businesss table. 6. All tables associated with a model must have a unique field which is the model name plus underscore id. The User model would have a primary key "user_id". 7. Controllers and their functions are directly related to the URLs so keep this in mind when naming them. 8. The URLs will have the following pattern. http://mydomain.com/Controller/Function/Parameters. There may be any number of parameters following the function and each should be separated by a slash (/). 9. Your views (templates) must have a .tpl extension. Getting Started Prerequisites: This version of MintyPHP will require the following: Apache with the mod_rewrite module, PHP5, and a MySQL database. Installation: The first thing to do is to install the MintyPHP files. Copy the contents of the zip, or gz, file to your document root. That is it! Configuration: Now we need to do a little configuration. Open the Config.php file (/app/config/Config.php). There are a few things we need to do to get MintyPHP working. Change the following values: 1. DB_HOST – The host name where the database resides. 2. DB_USER – The user name to connect to your database. 3. DB_PASS – The password to connect to your database. 4. DB_NAME – The name of the database. 5. ADMIN_EMAIL – Enter your email address. 6. DB_DIR – The directory to save the database backups to. 7. DB_DAYS – The number of days to keep database backups. 8. LOG_DIR – The directory to save the logs to. 9. LOG_DAYS – The number of days to keep log files. Now we are ready to start. There are some other things worth mentioning about configuration. If you are not satisfied with the default locations of the files you can make changes to these locations in the /app/config/common.inc.php file. The locations are set as global constants so if you are not familiar with global constants and the __autoload() function then it is recommended that you do not change these values. The database Before we can start building our site we must have our data model in place. Rather than bore you with the details I have provided the SQL to build the database at http://code.google.com/p/mintyphp/files/tutorial_db.sql The Main Template Now that we are installed and configured we can start on the main template for our site. We are not going to do anything really fancy here. This tutorial is about learning to use MintyPHP so you will not see anything pretty. The main template can be found at /app/view/template/template.tpl. This file will contain our header, footer, and main navigation. Anything you wish to appear consistent across the entire site should be placed into this file. Since we are creating a simple blog like website we will need to consider the components involved. We will have users, posts, and comments. Since this is a very simple application our navigation will most likely consist of user login and post archives. Our main page will show a small paragraph from each post and contain no more than 5 posts on the main page. The archive page will also show a small paragraph from each post but will list each post during that month. We will also create a “post” page where the users will be able to view the post in it‟s entirety along with other user‟s comments. template.tpl 1. Open the template.tpl file (or create it if it does not exist) in your favorite text editor. 2. Add the following markup to the file: {$title} {$meta} {$script} {$styles} {$content} This is the template.tpl file at its most basic. You can see that we have added some Smarty variables. These are key to the views in MintyPHP. The {$content} variable will be the contents of the subsequent templates that we create. The {$meta}, {$script}, and {$styles} variables will allow us to place the respective data within the head of the page where it belongs. This is done by defining these variables in our sub templates. This obviously doesn‟t do much for us so let‟s add a header, footer, and some navigation. The parts in green have been added. template.tpl {$title} {$meta} {$script} {$styles}

Archives

{$content}
Now we need to style our markup. I warn you, it isn‟t pretty and is all grey scale! It might give you flashbacks to the 80‟s. main.css (/app/view/resources/styles/main.css) a, a:visited{ color: #FFFFFF; text-decoration:none; } a:hover { color:#CCCCCC; } body { background-color: #CCCCCC; text-align:center; height:100%; } .clear { clear:both; } #content { float:left; margin:0; width:600px; height:inherit; padding:15px; } #header { background-color:#000000; padding:15px; margin:0px; color:#FFFFFF; } h1 { padding:0; margin:0; } #header h1 { font-size: 40px; padding:0px; margin:0px; } #leftNav { margin:0px; width:150px; float:left; padding: 10px; background-color:#666666; height:inherit; } #leftNav h3 { padding:0; margin:0; } #leftNav li { list-style:none; padding:0; margin:0; } #leftNav ul { margin:0 0 0 10px; padding:0; } #main { background-color: #FFFFFF; border: 5px solid #000000; width: 800px; padding:5px; text-align:left; font-family:Arial; height:inherit; } #topNav { color:#FFFFFF; background-color: #000000; text-align:right; border-top: 2px solid #FFFFFF; margin:0px; padding:3px; } #topNav ul { padding:0px; margin:0px; } #topNav li:before { content: "|"; margin-right:10px; } #topNav li { list-style:none; float:right; margin: 0 10px 0 0; padding:0px; } Okay, now we have our main template but we still can‟t do anything with it yet. Let‟s create a simple page to see our work so far. Navigate to the /app/view/pages directory and create a file called index.tpl. This is going to be the main entry point to our site. There is no need to create a controller or explicitly define a function to handle the index. Of course, if you wish to do so you definitely have the option to. Open the index.tpl site and add “

This is the index

” and save the file. Open your browser and type “localhost” into the address bar. There you have it! We can see that MintyPHP has automatically placed the content from the index.tpl file into our main template. Let‟s explore how this works. When a request is made for a page, say the index page in this instance, Apache‟s mod_rewrite module rewrites the request and sends it to the router.php file in the format of /router.php?p=XXX where XXX is anything that follows the domain in the URL. For our request there would be nothing. If we were to navigate to http://localhost/User/login then the request would be rewritten to /router.php?p=User/login. The router then checks to see if a controller has been defined for this request or if the request is for an existing file. This will generally be the first parameter following the domain. In the user example above the controller would be the UserController. The next part of the URL is the function to call which would be login() and anything following is passed to this function as an array of parameters. If a controller is not defined the PageController is then called. The PageController will check to see if the parameter passed is for a template. If the template is found then the page is rendered. If the template can not be found then the error.tpl page is displayed. That is quite a bit to take it but we can be happy for now to just know that it works. We can use this same functionality for any pages we do not need a controller for. That is to say, any pages that do not have business functionality or pages that only have static data. This only works from the /app/view/pages directory. To prove this lets create another template and call this one “hello.tpl”. Open this file and add “

Hello, World!

”. Now open your browser and type “localhost/hello” into the address bar. The Page Controller We have seen that static data will automatically be served for us via the PageController but what if we need additional functionality? It is very easy to add to the PageController to handle whatever needs we have. The next thing we will do is modify the PageController to handle a simple contact form which will allow users to send us an email. The first step is to actually create the form. In the /app/view/pages directory create a file called “contact.tpl” and also a stylesheet in /app/view/resources/styles called “forms.css”. Add the following to these files and view “localhost/contact”. contact.tpl {assign var=title value="Contact Me"} {assign var=styles value=""}

Send me an email

{$message}
Name
Email
Message
 
forms.css .formLabel { font-weight:bolder; text-align:right; float:left; margin:0; padding:5px; width:190px; } .formField { text-align:left; float:left; margin:0; padding:5px; width:390px; } #message { background-color:red; font-weight:bold; color:#FFFFFF; text-align:center; } Notice the use of {assign}. We have set two variables here that we referred to when creating our main template. The first, title, sets the title of the page (notice the title bar of the browser) and the second lets us include a template specific stylesheet that we want to use with this template. If you view the source you can see that the reference to the stylesheet is in the head of the document where it should be. So now we have our form and the PageController automatically loads the contact template for us but that is obviously not enough. Right now the page just submits to itself and will not send the email. The next step is to edit the PageController. Open the file (/app/controller/PageController.php) and let‟s examine the contents. We can see that there is one function defined, fetchPage(). This is the function that handles fetching our pages automatically. We do not want to touch this function. A couple things to take note of here are the fact that the function is static and it takes two parameters. All functions in your controllers should be static as the controller will never be instantiated. All functions that will handle standard requests must accept two parameters. The first parameter is the Smarty object that will render the page. The second is an array of data passed either via the URL or through the HTTP post. You do not need to be concerned with how this array is populated but you should know that all methods of data being passed will be included in this array. We are going to add a function to handle our contact form. This function will handle both the display of the form and sending the email once the form has been submitted. So the first thing we need to do is check to see if the form has been submitted. If it has, then we will send the email and display a message stating the email has been sent. If the form has not been submitted then we simply display the page. Add the following to the PageController. PageController.php public static function contact($smarty, $data) { // message to display after the form is submitted $message = ""; // has the form been submitted? if(isset($_POST['submit'])) { // form the body of our email $body = "

My Blog Contact Form Submission

"; $body .= $_POST['message']."

"; $body .= $_POST['name']."
".$_POST['email']; // This email class is pretty handy! $email = new Email(Config::ADMIN_EMAIL, "My Blog contact form"); $email->setfrom($_POST['email']); // We want to send an HTML email $email->setContentType(Email::$HTML); $email->send(); // the email has been sent so we set our message $message = "Your message has been sent!"; } // Any data we need to send back to our template we put into // an associative array and pass it to the showPage() function $data = array('message'=>$message); /* to render the page we call the showPage() function. * The first parameter is the smarty object * the second is the page to display * the third is our data to use in the template */ self::showPage($smarty, 'contact', $data); } Now when we submit our form we see the message stating that an email has been sent and if you have an SMTP server set up on your server you should see the email. So it is quite easy to add functionality to the PageController but is more likely that you will create your own controller to deal with a particular type of data. For instance, you may have a UserController that handles your users. You may have a PostController that will handle your user‟s posts. Creating your own controllers We are going to go ahead and create our own controller. This will be our UserController and we will add functionality to add, delete, log in, and log out users. In the /app/controller directory create a file called UserController.php. Don‟t forget the naming conventions. The controller name must start with a capital and be camel case. In the UserController file add the following: UserController.php So we have created a class called UserController which extends the functionality of Controller. It is important to remember to extend Controller or you will lose the functionality for rendering the templates. We have also added a function to handle logging in users. The problem is we don‟t have any users. Before we get into that lets create our login form. Notice that the second parameter is a little different. Instead of just the template name we have user/login. This tells our controller that our login template is inside a subdirectory called user. So let‟s create that file. login.tpl {assign var=title value="Please log in"} {assign var=styles value=""}

Please log in

{$message}
Username
Password
 
Nothing out of the ordinary here. We created our form, reused our forms stylesheet, set the page title, and added another variable that will populate the username file if the form is submitted with a bad password. Okay, the form is done but we still don‟t have any users. Let‟s create the User model. Creating Models This is the real power of MintyPHP. Currently we have a users table in our database and that table contains data for a single user, John Doe. We could add functionality to our UserController to query the database, look for the username, and verify the password…OR, we can extend the Model class and not have to do anything with the database. Create a file called User.php in the /app/model directory. Again, notice the naming convention. The filename starts with an uppercase letter and is the same name as the class. Add the following to the User.php file. User.php There isn‟t much there but what is there is quite powerful. We have defined a class called User which extends the Model class. We have also defined a variable called name. This is used by the functionality of the Model class and is needed in each class that extends Model. The value is simply the name of the class. There are a few different ways to instantiate a User object. We can either pass it an integer value which would be it‟s primary key, new User(345), or pass it an associative array of a field and value, new User(array(„username‟=>‟JohnDoe‟)), or we can create a user with all fields initialized to null. Now that we have a User model, let‟s go back to the UserController. We can now edit the login function to instantiate a User object and verify the password. Add the following to the login() function. UserController.php // handle the login of users public static function login($smarty, $data) { $message = ""; // the form has been submitted if(isset($_POST['submit'])) { // create a new user object by passing it a username $data = array('username'=>$_POST['username']); $user = new User($data); // if the password is null then the user does not exist if($user->password == null) { $message = "The username is invalid!"; // the password is incorrect } else if($user->password != trim($_POST['password'])) { $message = "The password provided is incorrect!"; // the correct password has been provided } else if($user->password == trim($_POST['password'])) { $_SESSION['user'] = $user->user_id; self::showPage($smarty, 'index', $data); } } $data = array('message'=>$message); if(isset($_POST['username'])) { $data['username'] = $_POST['username']; } self::showPage($smarty, 'user/login', $data); } Alright, we have filled in the functionality to login the user. Try logging in without a username and password. You should see a message stating that the username is not correct. Try adding the username “JohnDoe”. You should now see an error stating that the password is not correct and the username field should remain populated. Now try using the word “password” in the password field. You should be logged in and redirected to the index page. So there you have it. The three lines of code in our User class gave us the ability to retrieve the user‟s data without having to write any SQL. That is the true power of MintyPHP. Now that we have seen how the Model class works and how easily it can be extended to work with our Models, let‟s test some more of the automatic functionality that we get. The next thing we will do is create a form for new users to sign up. Add the following function to the UserController. UserController.php // handle user sign up public static function signup($smarty, $data) { $message = ""; // the form has been submitted if(isset($_POST['submit'])) { // check to see if the username exists already $user = new User(array('username'=>$_POST['username'])); if($user->user_id != null) { $message = "This username is already taken. Please try another."; // The username does not exist, create a new user } else { $user->username = $_POST['username']; $user->password = $_POST['password']; $user->first_name = $_POST['first_name']; $user->last_name = $_POST['last_name']; $user->save(); self::login($smarty, $data); } } $data = array( 'message'=>$message, 'username'=>$_POST['username'], 'first_name'=>$_POST['first_name'], 'last_name'=>$_POST['last_name'] ); self::showPage($smarty, 'user/signup', $data); } Again we try to create a user object by passing the constructor the username. If the user exists then the fields will be populated. If the user does not exist then the fields are initialized to null. This is why we check the user_id to see if it is null. Notice that we called the UserController‟s login function after we created the user. Now that we have the function we need the page associated with it. Create a file called signup.tpl in the /app/view/pages/user directory and add the following: signup.tpl {assign var=title value="Sign up"} {assign var=styles value=""}

Sign up

{$message}
First Name
Last Name
Username
Password
 
Try signing up with the username “JohnDoe”. Notice that you are redirected back to the form and notified that the username already exists. Now sign up with your own information. You should be logged in and redirected back to the index page. Check the database and verify that your information was saved in the users table. Pretty sweet, isn‟t it? What if we want to start collecting user email addresses when they sign up? With MintyPHP that is simple enough. The first step is to create the column in the database. Once that is done we need to add the appropriate field in the form and then set the email address in the UserController when we create the user. signup.tpl …
Last Name
Email
Username
… UserController.php … } else { $user->username = $_POST['username']; $user->password = $_POST['password']; $user->first_name = $_POST['first_name']; $user->last_name = $_POST['last_name']; $user->email = $_POST['email']; $user->save(); self::login($smarty, $data); } … $data = array( 'message'=>$message, 'username'=>$_POST['username'], 'first_name'=>$_POST['first_name'], 'last_name'=>$_POST['last_name'], 'email'=>$_POST['email'] ); Now if we sign up another user we can see that our email field is populated with the email address. The point is you can change the underlying data structure without having to change your model. That makes changes easier on you, the developer. While we are in the UserController lets go ahead and add functionality to log out and edit the user. UserController.php // log out the user public static function logout($smarty, $data) { unset($_SESSION['user']); self::showPage($smarty, 'user/login', $data); } // edit the user public static function edit($smarty, $data) { $user = new User(array('user_id'=>$_SESSION['user'])); if(isset($_POST['submit'])) { $user->first_name = $_POST['first_name']; $user->last_name = $_POST['last_name']; $user->email = $_POST['email']; if($_POST['password'] != null && $_POST['password'] != "") { $user->password = $_POST['password']; } $user->save(); self::showPage($smarty, 'index', $data); } $data = array('user'=>$user); self::showPage($smarty, 'user/edit', $data); } edit.tpl {assign var=title value="Edit your information"} {assign var=styles value=""}

Edit your information

First Name
Last Name
Email
Username
Password
 
The logout() function is pretty self explanatory. We unset the session variable so the user is no longer logged in and then send the user to the login page. The edit() function shows a form for the users to edit their information. We do a couple additional checks to ensure user data isn‟t overwritten. First we make sure the user is logged in, if not send them to the login page. Then we create a user object based on the id saved in the session. In our form we have the username field disabled and as a secondary precaution we do not overwrite what is already in the database, notice the absence of $user->username. Next, since we leave the password field empty inside the form for security reasons we check to see if it was left empty. If it is empty then we keep the password that we already have. Now that we have a way to login, signup, and edit users we need to edit our main template‟s navigation. Open the /app/view/template/template.tpl file and add/edit the following. template.tpl …
… The session data is automatically assigned to a Smarty variable called session. Here we check the $_SESSION[„user‟] variable that we populate when the user logs in and display different links depending on whether the user is logged in or not. We also get a preview into what is coming next, creating posts. The PostController Now that we have users they need to be able to do something. Before we create the PostController lets go ahead and create the Post model the same way we created our User model. Post.php Okay, now onto the PostController. We already saw in our navigation that we have a function called post so let‟s start there. The post() function will create a new Post and insert it into the database. Before we can do that we have to have a form for the user to enter the data. Let‟s creat the /app/view/pages/post/post.tpl file. We are also going to make a change to the forms.css file. post.tpl {assign var=title value="New Post"} {assign var=styles value=""}

New Post

Title
 
 
forms.css … textarea { width:350px; height:200px; } … Now we will add the post() function and the view() functions to the PostController. We are also going to create a function to make the title URL friendly so we can keep our pretty URLs. Here is the contents of the PostController. PostController.php user_id = $_SESSION['user']; $post->title = $_POST['title']; $post->url = self::makeURLTitle($_POST['title']); $post->text = $_POST['text']; $post->post_date = date("Y-m-d H:i:s"); $id = $post->save(); $data = array(„url‟=>$post->url); self::view($smarty, $data); } self::showPage($smarty, 'post/post', $data); } // view a post public static function view($smarty, $data) { // we are going to look up a post by the title URL $params = array('url'=>$data[0]); $post = new Post($params); // if the post is not found we display the error page if($post->post_id == null) { self::showPage($smarty, 'error', $data); } // the post is found so show it $data = array('post'=>$post); self::showPage($smarty, 'post/view', $data); } private static function makeURLTitle($title) { $title = preg_replace("/[^a-z\s\d]/i", "", $title); return str_replace(" ", "_", $title); } } ?> view.tpl {assign var=title value=$post->title} {assign var=styles value=""}

{$post->title}

{$post->text}
posted by: {$post->user_id}, {$post->post_date}
main.css … .creator { font-size:smaller; font-weight:bolder; } .title { font-size:20px; font-weight:bold; } .title { font-size:20px; font-weight:bold; } .title a, .title a:visited { color:#000000; } .title a:hover { color:#CCCCCC; } … There isn‟t really anything out of the ordinary here. The post function works the same way as the previous functions we have written for signing up and logging in users with the addition of calling the makeURLTitle() function which simply strips out non-alpha characters and replaces spaces with underscores. The view function is called after the post is saved. The view function is very simple. It uses the title passed in the URL to look for the post. If it can‟t be found then the error page is displayed. Adding Posts to the Index Page We can now add and view posts but how do we get to them. Right now we would have to guess the title which isn‟t very helpful at all. We are going to need to go back and revisit our PageController. Since we do not have an index() function we are going to need to add one. This function will need to do a little work before displaying the index page now. We are going to have to get 5 posts to display on the index page and we should probably display the 5 latest with the newest post first. MintyPHP provides a function in the Model class to help with this. The getAll() function will return an array of objects. This function takes a class name as the first parameter and the second parameter is an optional associative array used to limit the results. In our case our filter will be we only want 5 posts and we want the 5 newest. This may be a little redundant but we are also going to sort the returned array. This will help us ensure that the posts are in descending order by date. In our template we are going to loop through the array of Post objects and output the appropriate data. Smarty provides a convenient function for truncating data so we will use that to limit our post preview to only 150 characters. PageController.php public static function index($smarty, $data) { // we only want 5 posts and we want them ordered by date descending $params = array('ORDER BY'=>'post_date DESC', 'LIMIT'=>5); $posts = Post::getAll('Post', $params); // sort the posts by date using our comparison function usort($posts, array(self,'dateSort')); $data = array('posts'=>$posts); self::showPage($smarty, 'index', $data); } private static function dateSort($a, $b) { if(strtotime($a->post_date) == strtotime($b->post_date)) return 0; return (strtotime($a->post_date) > strtotime($b->post_date)) ? -1 : 1; } index.tpl {assign var=title value="My Blog"} {foreach from=$posts item=post}
{$post->text|truncate:150:"...":true}
posted by: {$post->user_id}, {$post->post_date}

{/foreach} Adding to the common code We are getting there. Now we can view our posts that we have made but we can‟t see any more than five. We need to create our archive links. Since this is site wide data we do not want to put it into a controller because then we would have to replicate it across each controller or call the same function over and over. Any functionality you wish to implement across the entire site can be included in the common.inc.php file. Since this is data related to posts we will write the function in the Post model but we will call it from common.inc.php so it is accessible everywhere. To do this we will use the DBHelper class along with the DataAccess class. The DBHelper class wraps the database functions to make it easier on you. Creating a DBHelper instance connects you to the database and the execute() function will perform your query. There is also an execute_params() function which takes in a query and an associative array. This function allows you to put place holders in your query which will be replaced by the values in the array. Post.php // gets the date of the oldest post public static function getOldest() { $db = new DBHelper(); $result = $db->execute(DataAccess::GET_OLDEST_POST_DATE); $row = mysqli_fetch_array($result) return $row['date']; } DataAccess.php You may be asking, “Why not just write the query and skip the DataAccess file?”. In this instance that may be okay but using the DataAccess file allows us to write a query once and use it in multiple places. If we need to change it for some reason there is only one place to make the change. Also, since the queries should not be changed by the code they are written as constants. Now on to the common.inc.php file. We have a function to give us the date of the oldest post but we need to actually do something with it. Add the following to the end of the file common.inc.php file. common.inc.php // Get the dates for the archives $oldestPost = strtotime(Post::getOldest()); $date = date('F, Y', $oldestPost); $dates = array($date); while(strtotime($date) < time()) { $month = date('m', strtotime($date)); $year = date('Y', strtotime($date)); $date = date('F, Y', mktime(0,0,0,$month+1, 1, $year)); $dates[] = $date; } $smarty->assign('archives', $dates); We simply get the oldest date and loop through increasing the month until we reach today. We then assign that array to a Smarty variable. Now we need to edit the the main template to display these dates as links. template.tpl …
    {foreach from=$archives item=date}
  • {$date}
  • {/foreach}
… The archive links are in place now and we need to create the archive() function in the PostController and the archive template to list the archived posts. Again since we are dealing with Post data we are going to create a function in the Post class to help us get the data we need. I know some people disagree with this approach and would rather put the function in the Controller. It is all a matter of preference and you should put these types of functions where you feel most comfortable. The getArchives() function is going to take in a start date which will be passed to the PostController via the URL as we have created in our archive links. It will then calculate a month from the start date and retrieve all posts between those dates. We will then populate an array of post objects and send them back to the PostController. Post.php // get archive posts by date public static function getArchives($startDate) { $month = date('m', strtotime($startDate)); $year = date('Y', strtotime($startDate)); $endDate = date('Y-m-d H:i:s', mktime(0,0,0,$month+1,1,$year)); $db = new DBHelper(); $params = array('%startDate%'=>$startDate, '%endDate%'=>$endDate); $postIDs = $db->execute_params(DataAccess::GET_ARCHIVES_BY_DATES, $params); $posts = array(); foreach($postIDs as $id) { $posts[] = new Post($id['post_id']); } return $posts; } The PostController does a little bit of trickery here. We are going to take the array of Post objects and render the index template rather than having to create a separate archive template. Notice the URL. It still says we are looking at the archives but the template is in fact the index. Reusability is always a good thing! Child classes Now we have a usable blog but you may have noticed that rather than a username in the “posted by” we have a user id. That is not very helpful. People are not going to know each other‟s user ids, in fact they will not even know their own. We need to get the username somehow and MintyPHP provides a very simple way to do so. I have mentioned instantiating child objects automatically when you create your object but we have yet to see this. We are going to alter our Post class to do this by telling it that it has a child class that is a user. There are two ways to register your children of your class. The first is the $children array. This tells the Model that you have one, and only one, child of that class. The second is the $hasMany array which tells the model that we can have any number of children that are of a given class. Let‟s see this at work. Post.php … public $name = "Post"; public $children = array( 'User' => array( 'className' => 'User', 'key' => 'user_id' ) ); ... The $children and $hasMany arrays follow the same format. The first thing we declare is the variable that we will store these objects in. In this case we have chosen “User”. This is the key. The value is another array which can have two key=>value pairs. The first is “className” whose value is the name of the class. The second is “key” whose value is the field to use when instantiating the object. In this case we are using the user_id. If a key is not provided then the primary key of the parent object would be used. In our example this would be the post_id. Now that we have told the Post class that it has a User child we need to go back to our templates and make the change to display the user name. Replace {$post->user_id} with {$post->User->username} in the post/view.tpl and the index.tpl templates. There you have it. When we create an instance of post we automatically get an instance of User as well based on the user_id in the post table. Pretty easy stuff. Conclusion Now that you know how MintyPHP works you should be able to add another function to the PostController to view all of a user‟s posts by clicking on their name. The solution will be posted on the web site if you have any trouble. As you can see, MintyPHP will speed up your development time by abstracting the data layer and making it easier for you to implement the MVC pattern. Have fun with it and feel free to post any recommendations that you have!

premium docs
Other docs by techmaster
2004 US Congress Law Code TableVI
Views: 87  |  Downloads: 0
sb0008a
Views: 59  |  Downloads: 0
Anti-Kickback and Stark I and II Statutes
Views: 283  |  Downloads: 8
i-102
Views: 85  |  Downloads: 0
ps1111
Views: 31  |  Downloads: 0
Indemnity _General Form_
Views: 122  |  Downloads: 4
amicus_data_tree
Views: 236  |  Downloads: 1
I-131Viet
Views: 82  |  Downloads: 0
Confidentiality Agreement[2]
Views: 231  |  Downloads: 17
order_unsealing_decl
Views: 71  |  Downloads: 0
2004 US Congress Law Code Title-38
Views: 57  |  Downloads: 0
2005 US Congress Law Code Title-02
Views: 218  |  Downloads: 0
Gilmore_20v._20Ashcroft_208.16.04[1]
Views: 40  |  Downloads: 0
20030618_opp_new_venue
Views: 114  |  Downloads: 0
2004 US Congress Law Code Title-17
Views: 90  |  Downloads: 0