SkinnyMVC is a light-weight, easy to learn, "skinny" development framework for PHP that enables the developer to implement the MVC architectural pattern, while maintaining maximum flexibility and performance of the application.

Create a simple blog with SkinnyMVC

This tutorial will show you howto create very simple blogging software using SkinnyMVC. The blogging software you will create by following this tutorial isn't meant to be extremely sophisticated, but is meant to teach you how to use SkinnyMVC while making something useful.

(It is assumed you already are comfortable developing software using PHP. And are comfortable using the Linux/Unix command line. And are also comfortable using the MySQL command line too.)

Now, before you start you will need to have your project located somewhere on your Linux/Unit server. We recommend you put it somewhere in the "/opt" directory. Perhaps somewhere like "/opt/myblogsoftware". Although you can call the directory (almost) anything you want. (We assume you are proficient enough to be able to create this directory without any instructions from us.) You will need to put the "skinnymvc.php" file you downloaded into that directory.


Step 1. After you copy "skinnymvc.php" into the directory where your blog software will reside, run the following command:

> php skinnymvc.php install

(Note that that ">" is meant to represent the command prompt, and is not actually meant to be typed out. The command prompt on your system may look different.)

After you have run that command, SkinnyMVC will create several directories and files for our project. (If you want to get an overview of what SkinnyMVC initially creates, click the following link to see the SkinnyMVC default directory structure.)

One of those directories will be "tmp". We need to make this directory accessible to the webserver:

> chmod 777 tmp -R

Step 2. Edit "config/settings.php" and set the database settings (of course, you must enter a username and password that actually works on your mysql server):

"dbdriver"        => "mysql",
"dbname"          => "myblog",
"dbhost"          => "127.0.0.1",
"dbuser"          => "user",       // <--- put something that actually works on your server
"dbpassword"      => "password",   // <--- put something that actually works on your server

(Note that we are not showing the entire contents of the "config/settings.php", but just the parts that you should edit.)


Step 3. Replace the contents of "config/schema.php" with the code you see below.

$model = array( 'user'=>array(
                              'id'=>array('type'=>'int', 'null'=>false, 'special'=>'auto_increment'),
                              'username'=>'varchar(255)',
                              'password'=>'varchar(255)',
                              '_PRIMARY_KEY'=>array('id'),
                ),
                'post'=>array(
                              'id'=>array('type'=>'int', 'null'=>false, 'special'=>'auto_increment'),
                              'title'=>'varchar(255)',
                              'body'=>'text',
                              'created'=>'timestamp',
                              'user_id'=>'int',
                              '_PRIMARY_KEY'=>array('id'),
                              '_FOREIGN_KEY'=>array('user_id'=>array('table'=>'user', 'field'=>'id')),
                ),
          );

Step 4. Run:

> php skinnymvc.php generateSQL

This will create a SQL file called "database.sql" and located in the directory "lib/skinnymvc/model/sql". (Or in other words, the newly create SQL file will be at "lib/skinnymvc/model/sql/database.sql".)

If you open that file -- if you open "lib/skinnymvc/model/sql/database.sql" -- the contents of the file should look like this:

CREATE TABLE IF NOT EXISTS `user` (
    `id` INT NOT NULL auto_increment,
    `username` VARCHAR(255) NOT NULL ,
    `password` VARCHAR(255) NOT NULL ,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS `post` (
    `id` INT NOT NULL auto_increment,
    `title` VARCHAR(255) NOT NULL ,
    `body` TEXT NOT NULL ,
    `created` TIMESTAMP NOT NULL ,
    `user_id` INT NOT NULL ,
    PRIMARY KEY (`id`),
    FOREIGN KEY (`user_id`) REFERENCES user(id)
) ENGINE=InnoDB;

Step 5. (Assuming that you are still in your main project directory) connect to your MySQL server, using the MySQL command line tool, and create the database structure with the following 3 commands:

mysql> CREATE DATABASE myblog;
mysql> USE myblog;
mysql> SOURCE lib/skinnymvc/model/sql/database.sql;

(Note again that those "mysql>" are meant to represent the MySQL command line tool command prompt, and are not actually meant to be typed out.)

Now, we will have a database called "myblog" with two tables: "user" and "post"

Let's create the first user for our blog, so that we can use this account to create blog posts.

mysql> INSERT INTO user SET username='admin', password='mypassword';

Exit the MySQL command line tool.


Step 6. Create the model files, by running the following command:

> php skinnymvc.php generateModel

(This will create 2 new files in "lib/skinnymvc/model" directory and 2 new files in "lib/skinnymvc/model/base" directory. Namely, it will create "lib/skinnymvc/model/User.php" and "lib/skinnymvc/model/Post.php" and will also create "lib/skinnymvc/model/base/BaseUser.php" and "lib/skinnymvc/model/base/BasePost.php". You can edit the fomer 2 PHP files, as we will do later in this tutorial, but don't edit the later two files!)


Step 7. Create a method that finds a user by the username and password. The appropriate place for this method is in the User model class located in "lib/skinnymvc/model/User.php".

   public static function getByUsernameAndPassword($username, $password) 
   {
     return self::selectOne(array('conditions'=> " WHERE username='$username' AND password='$password'"));
   }

Step 8. Now, we need to create some modules. The default module already exists, but we also need a module for posts. Run the following command:

> php skinnymvc.php createMod post

(Running this command will create the 3 directories: "modules/post", "modules/post/actions", and "modules/post/templates". And will create the 2 files: "modules/post/actions/actions.php" and "modules/post/templates/index.php".)


Step 9. Open the newly created action file in "modules/post/actions/actions.php" and create methods that get a list of posts (we will use executeIndex for this one) or a single post or create a new post:


   public function executeIndex($request)
   {
      $data = array();
      $posts = Post::select(array('order'=>' ORDER BY created DESC'));
      $data['posts'] = $posts;
      return $data;
   }

   public function executeShow($request)
   {
     $data = array();
     if(isset($request['GET']['id'])) {
       $id = $request['GET']['id'];
     } else {
       $data['errors'] = array('Missing post "id".');
       return $data;
     }
     
     $data['post'] = Post::selectOne(array('conditions'=>' WHERE id='.$id));

     return $data;
   }

   public function executeCreate($request)
   {
     if (empty($request['POST'])) {
        return array();
     }

     if (!isset($request['POST']['username']) || !isset($request['POST']['password']) 
         || (isset($request['POST']['username']) && isset($request['POST']['password']) 
             && !($user = User::getByUsernameAndPassword($request['POST']['username'],$request['POST']['password']))))
     {
       $data['errors'] = array('Wrong username or password.');
       $data['posted'] = $request['POST'];
       return $data;     
     }

     $post = new Post;
     $post->setTitle($request['POST']['title']);
     $post->setBody($request['POST']['body']);
     $post->setUserId($user->getId());
     $post->setCreated(date("Y-m-d H:i:s",time()));
     $post->save();
     $this->redirect('post', 'index');
   }

Step 10. Now, we need to create a template for each of those actions. First create the file "modules/post/templates/show.php" with the following contents:

<?php
 if(!isset($post)) $post=$skinnyData['post'];
?>
<div class="post">
 <div class="posttitle">
  <h3><a href="/post/show/?id=<?php echo $post->getId();?>"><?php echo htmlspecialchars($post->getTitle());?></a></h3>
  <div class="postbody">
   <?php echo $post->getBody(); ?>
  </div>
  <div class="postfooter">
   <?php
     $uid = $post->getUserId();
     $user = User::getByPK($uid);
     $userName = $user->getUsername();
     echo "Created by $userName on ".date($post->getCreated());
  ?>
  </div>
 </div>
</div>

(Note that the "show.php" template file corresponds with executeShow() method in the actions.php file.)

Next, we edit "modules/post/templates/index.php" and replace the conetns already in there with:

<div id="posts">
<?php
foreach($skinnyData['posts'] as $post) {
  include('../modules/post/templates/show.php');
} ?>
</div>
<a href="/post/create/">Create a new post</a>.

And last, we create the template for the executeCreate() action, called create.php (modules/post/templates/create.php):


<?php if (isset($skinnyData['errors']) && !empty($skinnyData['errors'])) {
?>
  <div class="error">
   <?php
      foreach ($skinnyData['errors'] as $error) {
        echo htmlspecialchars($error).'<br />';
      }
   ?>
  </div>
<?php }?>

  <form method="post" id="form1" action="/post/create/">
   <fieldset>
    <legend>Create a new post</legend>
    <p>
     <label for="username">
      Username:
     </label><br />
     <input type="text" name="username" id="username" value="" size="20" maxsize="50" />
    </p>
    <p>
     <label for="password">
      Password:
     </label><br />
     <input type="password" name="password" id="password" value="" size="20" maxsize="50" />
    </p>
    <p>
     <label for="title">
      Title:
     </label><br />
     <input type="text" name="title" id="title" value="" size="50" maxsize="255" />
    </p>
    <p>
     <label for="body">
      Body:
     </label><br />
     <textarea cols="60" rows="20" name="body" id="body"></textarea>
    </p>
    <p>
     <input type="submit" name="commit" value="Submit" />
    </p>
   </fieldset>
  </form>

(Note that this template file corresponds with executeIndex() method.)


Step 11. We are almost done!

We can create a link to the blog from our home page. The home page is located in the "default" module.
Go to the default module and edit the "index" template ("module/default/templates/index.php"):

  <div>
   <a href="/post/">Visit my awesome blog!</a>
  </div>

... and we need to set up the webserver (for apache in httpd.conf):

<VirtualHost *:80>
    ServerName   [your domain name]
    ServerAdmin  [your email]
    DocumentRoot [path to your project]/web
    php_value include_path .:[path to your project]
    <Directory "[path to your project]/web">
     AllowOverride All
     Allow from All
    </Directory>
</VirtualHost>

(Obviously, "[your domain name]", "[your email]", and "[path to your project]" will need to be changed to real values.)

The blog is now fully functional.

You can change the general layout by editing "templates/layout.php" and adding styles in "web/css/main.css"


Powered by SkinnyMVC       |       SkinnyMVC License       |       Developed by Radoslav Gazo and Charles Iliya Krempeaux