Wednesday, September 11, 2013

Creating A Simple PHP MVC Framework Part One (smarty version)

Written by: Lorenzo D. Alipio 

Introduction

This tutorial is about creating a simple PHP MVC framework. This framework can be use to power simple to advance websites. In the end of this tutorial, link for the demo will be provided. I will be using smarty and twitter bootstrap for the presentation layer to make our framework even extensible from back-end to the front-end. There is no intention in my part to re-invent any wheels that are already out there, but to give people the basic insights on how the PHP MVC framework works. If you want to see the screen shots of the application we are trying create, please take a look at this.


Requirements

1. XAMPP or equivalent Apache MySQL PHP servers installed on your computer. For alternative, there is an Apache MySQL PHP development environment called WAMP stack from  BITNAMI. I personally prefer XAMPP, because of the integrated Tomcat Apache for java applets development.
2. SMARTY template engine.
3. Twitter Bootstrap front-end framework.
4. A suitable PHP source code editor. I am currently using notepad++.
5. Optional (any) : NetBeans IDE, Eclipse, Aptana Studio 3.


MVC What?

The best definition I have read online is the "Separation of Concern" definition. MVC stands for Model View Controller. MVC is also referred by many as a software architecture pattern which separates the Model, View, and Controller being at the helm requesting or telling the view to change its state as it interacts with the users. On the other hand, Model can also let the View and Controller know of any changes. Although these three have separation of concerns, they are joined by one purpose, which is an effective application operations with traceable faults if it arises. I honestly believe that the Model and the View does the heavy lifting through the cycle of an event given to the application. The Model is primarily responsible for querying the data from the database, and the View makes these data aesthetically presentable to the browser as we see it today on many websites with the back-end written in MVC framework. If you prefer a lengthy type of definition, you can read it here.

OOPHP Why?

If you are a procedural php programmer, you can probably relate to how excruciating it is to debug 2000 ( a little exaggeration by me, but have seen this a lot though :) ) lines of PHP codes embedded between HTML tags. By writing our codes in object oriented, we can minimize the time consumed in debugging, re-writing codes on many pages.  The beauty of writing our codes in well organized structures and flows, we easily find the culprit. Not only that, we can make corrections only on the method/s of object/s causing the problem/s.

OOPHP allows us to write our codes in chunks, in groups, and in its own pages. We can extend other classes to make another child class, if the functions needed by our application is not dealt with by the parent class, and OOP guarantee us that a child class can be created as an extension of the parent class, and do whatever tasks not covered by the parent class.

These are the simplest explanation I can provide why Object Oriented is the backbone of creating an effective PHP MVC framework.

SHALL WE?

I hope I have provided enough information above. Now, let us start building our project.

Step One

Assuming that XAMPP and Notepad++ are already installed on your desktop, open the Notepad++ editor, paste codes below, and save it as projectcreator.php in xampp/htdocs/ directory. I strongly suggests to make sure your computer have an Internet connection for the smarty download.

 
<?php

/*
* 
* Copyright Lorenzo D. Alipio 
* 
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
* 
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
* 
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
* 
* projectcreator.php
*/


class CreateProject{

 private $controller = '/application/controller/';
 private $model = '/application/model/';
 private $view = '/application/view/';
 private $default_theme = '/web/themes/default/';
 private $theme_compile = '/web/themes/themes_compile/';
 private $temp = '/temp/';
 private $theme_configs= '/web/themes/themes_configs/';
 private $smartyUrl = 'http://www.smarty.net/files/Smarty-3.1.14.zip';
 private $dir;
 private $projectName ;

public function __construct(){
 $this->dir = array($this->controller, $this->model, $this->view, $this->default_theme, $this->theme_compile, $this->temp,$this->theme_configs);
 
     $this->projectName = 'mvcproject';

    }

public function createDir(){

 foreach($this->dir as $item){
  if(!file_exists($this->projectName.$item)){
  $this->setProject($this->projectName.$item);
  
  }
  
  else{
  echo $this->projectName.$item.' already exists
';
  }
 }
}

public function setProject($project){

 if(!file_exists($project)){
 mkdir($project, 0, true);
 echo '
'. $project .' Created';
 }
 if(!file_exists($this->projectName.'/smarty.zip')){
 $this->downloadSmarty($this->smartyUrl);
  echo '<br/> Smarty Downloaded';
 }
}

public function unZipfile(){
$file = $this->projectName.'/smarty.zip';
if(file_exists($this->projectName.'/temp')){

if(!file_exists($this->projectName.'/temp/smarty/')){
 mkdir($this->projectName.'/temp/smarty/', 0, true);
 }
 if (is_resource($file)) {
  while ($zip_entry = zip_read($file)) {
    $fp = fopen($this->projectName.'/temp/smarty/'.zip_entry_name($zip_entry), "w");
    if (zip_entry_open($file, $zip_entry, "r")) {
      $buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
      fwrite($fp,"$buf");
      zip_entry_close($zip_entry);
      fclose($fp);
    }
  }
  zip_close($file);
}
 


}
}


public function downloadSmarty($url){
    $fp = fopen($this->projectName.'/smarty.zip', 'w');
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FILE, $fp);
    $data = curl_exec($ch);
    curl_close($ch);
    fclose($fp);
 
 }
public function createJson(){


 $json ='{';
 $json .= "\n\n\t"; 
 //$json .= "\t";
 $json .= '"require": {';
 $json .= "\n\t\t";
 $json .= '"symfony/class-loader": "2.4.*@dev",';
 $json .= "\n\t\t";
 $json .= '"symfony/http-foundation": "2.3.*@dev",';
  $json .= "\n\t\t";
 $json .= '"phpunit/phpunit": "3.7.*",';
  $json .= "\n\t\t";
 $json .= '"swiftmailer/swiftmailer": ">=4.2.0,<4 data-blogger-escaped-.3-dev="" data-blogger-escaped-.="}" data-blogger-escaped-file_exists="" data-blogger-escaped-if="" data-blogger-escaped-json="" data-blogger-escaped-this-="">projectName.'/composer.json')){
 
         $writeJsonFile = fopen($this->projectName.'/composer.json',"w");
         fwrite($writeJsonFile,$json);
         fclose($writeJsonFile); 
 
 }
}


}

$object = new CreateProject();
$object->createDir();
//$object->createJson();
//$object->unZipfile();


?>

By default, our project  'mvcproject', you can change this to whatever name you want. Change the value of $this->projectName in the constructor.

<?php

$this->projectName = 'mvcproject';

?>

If your computer have no Internet connection,  change this part of the code
$this->downloadSmarty($this->smartyUrl);
  echo 'Smarty Downloaded';

to this
//$this->downloadSmarty($this->smartyUrl);
  //echo 'Smarty Downloaded';


I left the createJson() and unZipfile commented  for now. I will be discussing them later. Save the file above and direct your browser to http://localhost/projectcreator.php. If everything worked as plan, there should be a new directories in the htdocs directory

htdocs
    + mvcproject
          + application
           |     + controller
           |     + model
           |     + view
           +temp
           +web
           |    +themes
           |         +default
           |         +themes_compile
           |         +themes_configs
           composer.json *for later
           smarty.zip *if connected to the Internet

That concludes the part one of this tutorial series.  Read part two ....      


1 comment:

  1. public function createJson(){

    has an error.....



    PHP Parse error: syntax error, unexpected '')){' (T_CONSTANT_ENCAPSED_STRING) in /XXXXX/XXXXXXXXXX/websites/PROJ_CREATE_MVC/projectcreator.php on line 126


    I've treied adding the ' but not finding where.

    ReplyDelete