Sunday, September 29, 2013

Creating A Simple PHP MVC Framework Part 7C ,First Application- Template files (smarty version)

This is the last section of the template tutorial series. In this section, we will be creating the remaining template files for our application.
filename: web/themes/default/play.tpl
 
{% *Copyright: Lorenzo D. Alipio* %}
 {% *file: web/themes/default/play.tpl* %}  
 {% extends file="web/themes/default/main.tpl" %}  
 {% block name=title %}Playing {% $content.title %}{% /block %}  
 {% block name=meta %}{% /block %}  
 {% block name=metad %}{% /block %}  
 {% block name=general %}  
 <div class="span8">  
 <h4>Playing {% $content.title %}</h4>  
 <iframe id="youtube" width="100%" height="480" src="//www.youtube.com/embed/{% $content.v_id %}" frameborder="0" allowfullscreen></iframe>  
 <br/>  
 <!-- Related Videos -->  
 <div id="related">  
 <h3 class="title">Related Videos</h3>  
 <ul>  
 {% section name=item loop=$content.related %}  
 <li>  
 <a href="javascript:loadThisVideo('youtube','http://www.youtube.com/embed/{% $content.related[item].v_id %}?rel=0&amp;hd=1')"><img src="{% $content.related[item].thumb %}" title="{% $content.related[item].title %}"/></a>  
 </li>  
 {% /section %}  
 </ul>  
 </div>  
 <!-- end of related -->  
 </div>  
 <div class="span4">  
 <h5 class="title">Recommended Videos</h5>  
 <div id = "thumb3">  
 <ul>  
 {% section name=item loop=$content.video %}  
 <li>  
 <a href="javascript:loadThisVideo('youtube','http://www.youtube.com/embed/{% $content.video[item].v_id %}?rel=0&amp;hd=1')"><img src="{% $content.video[item].thumb %}"/></a>  
 <br/>  
 {% $content.video[item].title %}  
 <br/>  
 </li>  
 {% /section %}  
 </ul>  
 </div>  
 </div>  
 {% /block %}  


That concludes the template files creation. So far so  good, we are now finished with the template files. Next will be the youtube API class. You can view the screenshots of our application  here.

Creating A Simple PHP MVC Framework Part 7B ,First Application- Template files (smarty version)

Written by Lorenzo D. Alipio (open source developer) 

(if you need professional help in implementing Smarty template engine, you can contact me here). 

In our last series part 7A, we created the parent template for our application. In this series, we will be creating the about.tpl, categories.tpl, index.tpl, and latest.tpl.

filename: web/themes/default/about.tpl
{% *Copyright: Lorenzo D. Alipio* %}
{% extends file="web/themes/default/main.tpl" %}

{% block name=title %}About Us{% /block %}
{% block name=meta %}{% /block %}
{% block name=metad %}{% /block %}

{% block name=general %}

{% $content.about %}


{% $content.name %}


{% $content.email %}
{% /block %}



filename: web/themes/default/categories.tpl
{% extends file="web/themes/green/main.tpl" %}
{% block name=title %}Music Video Categories{% /block %}
{% block name=meta %}{% /block %}
{% block name=metad %}{% /block %}

{% block name=general %}
 <h1 class="title" >{% $content.categoryHeader %}</h1> 
{% /block %}


filename: web/themes/default/index.tpl
 {% *2013 Copyright Lorenzo D. Alipio <ldalipio@msn.com>* %}  
 {% extends file="web/themes/default/main.tpl" %}  
 {% block name=title %}About Us{% /block %}  
 {% block name=meta %}{% /block %}  
 {% block name=metad %}{% /block %}  
 {% block name=general %}  
 <div class="span8">  
 <h4 class="title" >About this Demo Script</h1>  
 {% $content.content['first_p'] %}  
 <ul>  
 {% foreach $content.content['lists'] as $item %}  
 <li>{% $item %}</li>  
 {% /foreach %}  
 </ul>  
 <h5 class="title">Additional Information</h5>  
 <br/>  
 {% $content.content['more_info'] %}  
 <br/>  
 </div>  
 <div class="span4">  
 <h4 class="title">Demo Map</h5>  
 <ul>  
 <li><a href="categories.php"><h5 class="title">Categories</h5></a></li>  
 <li><a href="toprated.php"><h5 class="title">Top Rated</h5></a></li>  
 <li><a href="mostviewed.php"><h5 class="title">Most Viewed</h5></a></li>  
 <li><a href="latest.php"><h5 class="title">Latest Video</h5></a></li>  
 </ul>  
 </div>  
 {% /block %}  



filename: web/themes/default/latest.tpl
 {% extends file="web/themes/green/main.tpl" %}  
 {% block name=title %}{% /block %}  
 {% block name=meta %}{% /block %}  
 {% block name=metad %}{% /block %}  
 {% block name=title %}{% /block %}  
 {% block name=thumb %}  
 <h3 class="title">Video Count {% $content.count %}</h3>  
 <div id = "thumb2">  
 <ul>  
 {% section name=item loop=$content.video %}  
 <li>  
 <a href="play.php?vid={% $content.video[item].v_id %}&title={% $content.video[item].title|escape:'htmlall' %}&cat={% $content.cat %}"><img src="{% $content.video[item].thumb %}"/></a>  
 <br/>  
 {% $content.video[item].title %}  
 <br/>  
 {% $content.video[item].desc %}  
 <br/>  
 </li>  
 {% /section %}  
 </ul>  
 </div>  
 {% /block %}  
 {% block name=paginate %}{% $content.pagination %}{% /block %}  

Noticed the codes above, all of our template files inherited the properties of  the main.tpl file and filled the blocks as needed on the page.

Friday, September 27, 2013

Creating A Simple PHP MVC Framework Part 7A ,First Application- Parent Template (smarty version)

Written by Lorenzo D. Alipio (open source developer) 

(if you need professional help in implementing Smarty template engine, you can contact me here).

What makes Smarty and Twig template engines standout from the rest of the crowd is that both of these template engines support template inheritance.


In the earlier section of this tutorial, I have suggested that we will be using bootstrap as our html framework. The presentation layer of our simple MVC is outlined by simple diagram below

controllerClass instantiate our view class --> viewClass assign the data to the template engine smarty --> smarty uses the main.tpl as parent template.

Let us create the main.tpl file. This is the parent template file of our application.

Filename: web/themes/default/main.tpl

 <!DOCTYPE html>  
 <html lang="en">  
 <head>  
 <meta http-equiv="content-type" content="text/html;charset=utf-8" />  
                <!-- page title block -->  
 <title>{% block name=title %}{% /block %}</title>  
                <!-- /end of page title block -->  
 <meta name="viewport" content="width=device-width, initial-scale=1.0">  
 <meta http-equiv="Content-Type" content="text/html; charset=windows-1251" />  
                <!-- robots block -->  
      {% block name=robots %}{% /block %}  
                <!-- /end of robots block -->  
 <meta name="keywords" content="{% block name=meta %}{% /block %}">  
 <meta name="robots" content="all">  
 <meta name="revisit" content="1 day">  
                <!-- additional css block -->  
      {% block name=style %}  
 <style>  
 #player {  
  margin:0 auto;  
  float:none;  
 }  
 </style>  
      {% /block %}  
                <!-- end of additional css block -->  
                <!-- Optional javascript block -->  
      {% block name=jscript %}{% /block %}  
                <!-- /end of optional javascript block -->  
 <link href="http://{% $content.sitepath %}themes/default/css/bootstrap.css" rel="stylesheet">  
 <link href="http://netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css" rel="stylesheet">  
 <link href="http://{% $content.sitepath %}themes/default/css/bootstrap-responsive.css" rel="stylesheet">  
    <!-- HTML5 shim, for IE6-8 support of HTML5 elements -->  
    <!--[if lt IE 9]>  
  <script src="../assets/js/html5shiv.js"></script>  
    <![endif]-->  
    <!-- Fav and touch icons -->  
   <link rel="apple-touch-icon-precomposed" sizes="144x144" href="http://{% $content.sitepath %}themes/default/ico/apple-touch-icon-144-precomposed.png">  
   <link rel="apple-touch-icon-precomposed" sizes="114x114" href="http://{% $content.sitepath %}themes/default/ico/apple-touch-icon-114-precomposed.png">  
   <link rel="apple-touch-icon-precomposed" sizes="72x72" href="http://{% $content.sitepath %}themes/default/ico/apple-touch-icon-72-precomposed.png">  
   <link rel="apple-touch-icon-precomposed" href="http://{% $content.sitepath %}themes/default/ico/apple-touch-icon-57-precomposed.png">  
   <link rel="shortcut icon" href="http://{% $content.sitepath %}themes/default/ico/favicon.png">  
    <!-- /end of Fav and touch icons -->  
    <!-- link to the theme style css file -->  
  <link href="http://{% $content.sitepath %}themes/default/css/green.css" rel="stylesheet">  
    <!-- /end of theme style css file -->  
    <!--[if gte IE 9]>  
  <style type="text/css">  
   .gradient {  
     filter: none;  
   }  
  </style>  
  <![endif]-->                 
 {% block name=style %}{% /block %}                 
                <!-- jquery code block -->   
 <script src="http://code.jquery.com/jquery-1.9.1.js"></script>  
 <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>  
                <!-- /end of jquery code block -->  
 <script>  
 $(function() {  
 $( "#videos" ).tabs();  
 });  
 </script>  
 <script>  
  function resizeCaller(){var a=new Array;for(i=0;i<iframeids.length;i++){if(document.getElementById)resizeIframe(iframeids[i]);if((document.all||document.getElementById)&&iframehide=="no"){var b=document.all?document.all[iframeids[i]]:document.getElementById(iframeids[i]);b.style.display="block"}}}function resizeIframe(a){var b=document.getElementById(a);if(b&&!window.opera){b.style.display="block";if(b.contentDocument&&b.contentDocument.body.offsetHeight)b.height=b.contentDocument.body.offsetHeight+FFextraHeight;else if(b.Document&&b.Document.body.scrollHeight)b.height=b.Document.body.scrollHeight;if(b.addEventListener)b.addEventListener("load",readjustIframe,false);else if(b.attachEvent){b.detachEvent("onload",readjustIframe);b.attachEvent("onload",readjustIframe)}}}function readjustIframe(a){var b=window.event?event:a;var c=b.currentTarget?b.currentTarget:b.srcElement;if(c)resizeIframe(c.id)}function loadThisVideo(a,b){if(document.getElementById)document.getElementById(a).src=b}var iframeids=["myframe"];var iframehide="yes";var getFFVersion=navigator.userAgent.substring(navigator.userAgent.indexOf("Firefox")).split("/")[1];var FFextraHeight=parseFloat(getFFVersion)>=.1?16:0;if(window.addEventListener)window.addEventListener("load",resizeCaller,false);else if(window.attachEvent)window.attachEvent("onload",resizeCaller);else window.onload=resizeCaller  
 </script>  
 </head>  
 <body>  
 <div class="navbar navbar-inverse navbar-fixed-top">  
    <div class="navbar-inner-green">  
     <div class="container">  
      <button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">  
       <span class="icon-bar"></span>  
       <span class="icon-bar"></span>  
       <span class="icon-bar"></span>  
      </button>  
      <a class="brand" href="#">Lorenzo Alipio Demo Script</a>  
      <div class="nav-collapse collapse">  
       <ul class="nav">  
        <li class="active"><a href="index.php"><i class="icon-home icon-large" ></i> Main</a></li>  
        <li><a href="#about">About</a></li>  
        <li><a href="#contact">Contact</a></li>  
                 <li class="dropdown"><a href="#" class="dropdown-toggle" data-toggle="dropdown">Media<b class="caret"></b></a>  
             <ul class="dropdown-menu">  
                               <li class="dropdown-submenu">  
                               <a tabindex="-1" href="#">Video</a>  
                               <ul class="dropdown-menu">  
              <li><a href="latest.php">Latest</a></li>  
              <li><a href="toprated.php">Top Rated</a></li>  
              <li><a href="mostviewed.php">Most Viewed</a></li>  
                                <li><a href="categories.php">Categories</a></li>  
                                </ul>  
                                </li>  
                               <li class="dropdown-submenu">  
                               <a tabindex="-1" href="#">Audio</a>  
                               <ul class="dropdown-menu">  
                               <li><a href="#">Latest</a></li>  
                               </ul>  
                               </li>  
                               <li class="dropdown-submenu">  
                               <a tabindex="-1" href="#">Photos</a>  
                               <ul class="dropdown-menu">  
                               <li><a href="#">Latest Photos</a></li>  
                               </ul>  
                               </li>  
                               <li class="dropdown-submenu">  
                               <a tabindex="-1" href="#">Blog</a>  
                               <ul class="dropdown-menu">  
                               <li><a href="#">Latest Entries</a></li>  
                               </ul>  
                               </li>  
             </ul>  
            </li>  
                 {% block name=accountmenu %}{% /block %}  
       </ul>  
                <form class="navbar-search pull-right" method="get" action="video.php">  
      <input type="text" name="q" class="search-query span2" placeholder="Search">  
     </form>  
      </div><!--/.nav-collapse -->  
     </div>  
    </div>  
   </div>  
  <div class="container">  
           {% block name=mtitle %}{% /block %}  
      <div class="row">  
      <div id="videos">    
       {% block name=page_tabmenu %}  
       <!-- page tab menu block -->  
       {% /block %}  
                <!-- featured begins -->  
 <div id="featured" class="span12 row-fluid">  
                {% block name=featured %}{% /block %}  
 </div>   
                <!-- latest begins -->  
 <div id="latest" class="span12 row-fluid">  
                {% block name=latest %}{% /block %}  
 </div>  
                <!-- mostviewed begins -->  
 <div id="mostviewed" class="span12 row-fluid">  
                {% block name=mostviewed %}{% /block %}  
 </div>  
 </div>  
 </div>  
                <!-- /end of tab content blocks -->  
                <!-- content blocks of all types -->  
 <div class="span12 row-fluid">  
                {% block name=thumb %}{% /block %}  
 </div>  
 <div class="span12 row-fluid">  
                {% block name=login %}{% /block %}  
 </div>  
 <div class="span12 row-fluid">  
                {% block name=general %}{% /block %}  
 </div>  
                <!-- show pagination here if needed -->  
 <div class="row">  
 <div class="span12 row-fluid">  
 <table width = "100%" ALIGN="center">  
 <tr>  
 <td align="center" ><div class='paginate'>  
                {% block name=paginate %}{% /block %}  
    </div>  
 </td></tr></table>  
 <!-- EOF pagination section -->  
 </div>  
 </div>  
  <div id="push"></div>  
 </div>  
 <div id="footer">  
    <div class="container">  
      <div class="row">  
        <div class="span12 row-fluid pagination-centered">  
          <div class="span6"><div class="bottombox text-left"><h1 class="footer">Lorenzo D. Alipio</h1> &copy; All rights reserved.  
 Powered by Lorenzo D. Alipio Framework. </div></div>  
          <div class="span3"><div class="bottombox"><h5 class="footer">Archives</h5></div></div>  
          <div class="span3"><div class="bottombox"><h5 class="footer">Social</h5>  
              <div class="social_icons">  
                <ul>  
                  <li><a href="#"><img src="http://{% $content.sitepath %}themes/default/social/blogger.png"></a></li>  
                  <li><a href="#"><img src="http://{% $content.sitepath %}themes/default/social/facebook.png"></a></li>  
                  <li><a href="#"><img src="http://{% $content.sitepath %}themes/default/social/youtube.png"></a></li>  
                  <li><a href="#"><img src="http://{% $content.sitepath %}themes/default/social/twitter.png"></a></li>  
                  <li><a href="#"><img src="http://{% $content.sitepath %}themes/default/social/digg.png"></a></li>  
                  <li><a href="#"><img src="http://{% $content.sitepath %}themes/default/social/stumbleupon.png"></a></li>  
                  <li><a href="#"><img src="http://{% $content.sitepath %}themes/default/social/vimeo.png"></a></li>  
                  <li><a href="#"><img src="http://{% $content.sitepath %}themes/default/social/rss.png"></a></li>  
                </ul></div>   
            </div></div>  
        <div class="spane12 row fluid">  
        <footer>  
                <!-- display copyright -->  
                {% block name=copyright %}{% /block %}   
 </footer>  
        </div>  
        </div>  
      </div>    
 </div>  
 </div>  
 </div>  
                <!-- can use this block for much needed javascript on page -->  
                {% block name=jscript1 %}{% /block %}  
   <script src="http://{% $content.sitepath %}themes/default/js/bootstrap-transition.js"></script>  
   <script src="http://{% $content.sitepath %}themes/default/js/bootstrap-alert.js"></script>  
   <script src="http://{% $content.sitepath %}themes/default/js/bootstrap-modal.js"></script>  
   <script src="http://{% $content.sitepath %}themes/default/js/bootstrap-dropdown.js"></script>  
   <script src="http://{% $content.sitepath %}themes/default/js/bootstrap-scrollspy.js"></script>  
   <script src="http://{% $content.sitepath %}themes/default/js/bootstrap-tab.js"></script>  
   <script src="http://{% $content.sitepath %}themes/default/js/bootstrap-tooltip.js"></script>  
   <script src="http://{% $content.sitepath %}themes/default/js/bootstrap-popover.js"></script>  
   <script src="http://{% $content.sitepath %}themes/default/js/bootstrap-button.js"></script>  
   <script src="http://{% $content.sitepath %}themes/default/js/bootstrap-collapse.js"></script>  
   <script src="http://{% $content.sitepath %}themes/default/js/bootstrap-carousel.js"></script>  
   <script src="http://{% $content.sitepath %}themes/default/js/bootstrap-typeahead.js"></script>  
                <!-- 2nd javascript block for javascript that needs to be written on the page -->  
                {% block name=jscript2 %}{% /block %}       
 </body>  
 </html>  



This conclude the tutorial on parent template creation. Next will be the creation of  about.tpl.

Wednesday, September 18, 2013

Creating A Simple PHP MVC Framework Part 6B, First Application- Youtube API (smarty version)

Written by Lorenzo D. Alipio (open source PHP developer) 

This is the part 6B of our tutorial series. In this segment, we will be creating these controller files. These are the files we were not able to create in Part 6A.

1.MostviewedController.php
2.PlayController.php
3.TopRatedController.php

The Views we need to create
1.ViewClass.php

Filename: controller/MostviewedController.php
<?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.
* 
* MostviewedController.php
*/

class MostviewedController extends Controller {

 public $q = "funnies";
 public $index = '1';
 public $orderby = "published";
 public $i = 48;
 public $count ='';
 function __construct() {
  
  parent::__construct();
  Use_Class::autoload(YOUTUBE);
  
 }

public function index(){

 
 if(isset($_GET['q'])){
 $q = $_GET['q'];
    $q = preg_replace('/[[:space:]]+/', '/', trim($q));
    $q = str_replace('/', '+', $q);
 $index = $_GET['start-index'];
 $orderby = $_GET['orderby'];
 $i = 25;
}
else{
  $q = "Metallica";
  $index = "1";
  $orderby = "published";
  $i = 25;
}
$object = new YoutubeVideo($q,$index,$orderby,$i);
 $video = array(
     'count'=> $object->getCount(),
     'video'=> $object->getVideo(),
     'sitepath'=>SITEPATH,
     'cat' => $q,
     'pagination'=>$object->pagenate('mostviewed.php')
  );
 
 return $this->view->set_content($video,'latest.tpl');
 
}


}  





Filename : controller/PlayController.php
<?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.
* 
* PlayController.php
*/
class PlayController extends Controller {
 
 public $v_id;
 public $title;
 public $description ;
 public $q = "funnies";
 public $index = '1';
 public $orderby = "viewCount";
 public $i = 10;
 public $count ='';

 public function __construct() {

  parent::__construct();
  Use_Class::autoload(YOUTUBE);
  

  if(isset($_GET['vid'])){
   $this->v_id = filter_var($_GET['vid'], FILTER_SANITIZE_STRIPPED);
   $this->title = filter_var($_GET['title'], FILTER_SANITIZE_STRIPPED);
   $this->category = filter_var($_GET['cat'], FILTER_SANITIZE_STRIPPED);
   $this->q = $this->category;
   // set video data feed URL
         

        
    
   
  }

 
 }

 public function index(){
  
  $object = new YoutubeVideo($this->q,$this->index,$this->orderby,$this->i);
  $relatedObject = new YoutubeVideo($this->q, 2 ,$this->orderby,15);
  
  $video = array(

      'v_id' => $this->v_id,
      'title' => $this->title,
      'video'=> $object->getVideo(),
      'related'=>$relatedObject->getVideo(),
      
      'sitepath' => SITEPATH,
      'cat' =>$this->category
  );

  return $this->view->set_content($video,'play.tpl');

 }


}




filename: TopratedController.php
<?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.
 * File: application/controller/TopratedController.php
 */

class TopratedController extends Controller {

 public $q = "toprated";
 public $index = '1';
 public $orderby = "published";
 public $i = 48;
 public $count ='';
 function __construct() {
  
  parent::__construct();
  Use_Class::autoload(YOUTUBE);
  
 }

public function index(){

 //$object = Ini_object::instance('YoutubeVideo');
 if(isset($_GET['q'])){
 $q = $_GET['q'];
    $q = preg_replace('/[[:space:]]+/', '/', trim($q));
    $q = str_replace('/', '+', $q);
 $index = $_GET['start-index'];
 $orderby = $_GET['orderby'];
 $i = 25;
}
else{
  $q = "Aerosmith";
  $index = "1";
  $orderby = "published";
  $i = 25;
}

$object = new YoutubeVideo($q,$index,$orderby,$i);
 
 $video = array(
     'count'=> $object->getCount(),
     'video'=> $object->getVideo(),
     'sitepath'=>SITEPATH,
     'cat' => $q,
     'pagination'=>$object->pagenate('toprated.php')
  );
 
 return $this->view->set_content($video,'latest.tpl');
 
}


}  





filename: view/ViewClass.php
<?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.
 * File: application/view/ViewClass.php
 */
Class View{

public function  __construct(){
 
 if(TPL === 'Smarty'){
 Ini_object::instance('Smarty');
 $this->tpl = Ini_object::instance('Smarty');
 $this->tpl->left_delimiter = '{% ';
  $this->tpl->right_delimiter = ' %}';
 $this->tpl->template_dir = ( THEME_DIR );
  $this->tpl->compile_dir  = ( THEME_COMPILE );
  $this->tpl->caching = 0;
  $this->tpl->setCompileCheck(true);
  $this->tpl->cache_dir    = ( THEME_CACHE );
  $this->tpl->config_dir   = ( THEME_CONFIG ); 
}

else if(TPL ==='Twig'){
  Use_Class::useFile(TWIG_LOADER);
  Twig_Autoloader::register();
   ## define our template directory location
  $loader = new Twig_Loader_Filesystem('templates');

  ##  initialize Twig environment with cache enabled
  $twig = new Twig_Environment($loader, array(
    'cache'       => TWIG_CACHE,
    'auto_reload' => true
  ));
}

}
/*
* TO DO integrate TWIG 
*
*/

public function set_content($content=array(),$templateName = null){
 
 

  $this->tpl->assign('content', $content);
  return $this->tpl->display(THEME .$templateName);

 
 
 }
 
 
} 



Notice, how the ViewClass.php was coded, we are setting our own delimiters for our smarty template engine. We will be using {%  and  %} because I am trying to build this framework to be able to use twig template engine. This conclude the Part 6B. Next time we will be writing the parent template file, the child template files. Hopefully, we can test our simple MVC implementing youtube API v2.

Tuesday, September 17, 2013

Creating A Simple PHP MVC Framework Part 6A, First Application- Youtube API (smarty version)

Written by Lorenzo D. Alipio (open source developer)  

 
We are now in part 6A of this tutorial series, and I am pretty excited to write a simple application for our simple PHP MVC framework. After writing this simple application, you will probably agree with me that not all applications should be built upon the much bigger frameworks such as CodeIgniter, Kohana, Zend, Symfony. I will be writing the same application in Kohana  and CodeIgniter in the upcoming tutorials. Just to demonstrate how it is done on a bigger frameworks.

Our simple application will not be needing a database, because it is solely based on the Youtube API version 2. I honestly believe that if we can implement it on youtube API, I don't see any reason for us to implement other types of application to be build on this simple framework.

Here is the plan. We will be writing all of the controller, model, view pages first, and then create the template files ustilizing the smarty. This application will have a functional search class, pagination, and play page.

The Controllers we need to create
1. AboutController.php
2. CategoriesController.php
3.IndexController.php
4.LatestController.php
5.MostviewedController.php
6.PlayController.php
7.TopRatedController.php

The Models we need to create
1. Since there is no Database for our first application, we will not be creating any model file.

The Views we need to create
1.ViewClass.php


Filename:  application/controller/AboutController.php
<?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.
 * AboutController.php
 */



class AboutController extends Controller{

public function __construct(){
 parent::__construct();
 
 }
 
private function aboutContent(){
 return array(
  'about'=> 'Created with L.D.Alipio light MVC, twitter bootstrap, smarty template engine.',
  'email' => 'YourEmail@domain.com',
  'name' => 'Lorenzo Alipio',
  'motto' => 'You can do it (not like the Nike though.)',
  'sitepath'=>SITEPATH
  );
 
} 
public function index(){
 
   return $this->view->set_content(self::aboutContent(),'about.tpl');
 
}
 
}


Since this is the very first functional controller of our application, I would like to take this opportunity to explain the basics of what, why, and where all these things are going to go, and I am really hoping I can explain them with clarity.


Please take a look at the codes below



class AboutController extends Controller{

public function __construct(){
 parent::__construct();
 
 }

The AboutController is named after the job or function of this controller. So if we are going to write a controller responsible for member's registration, we can named if as RegisterController.php. We should always develop some form of naming convention for the purpose of clarity and quick identification of our classes and files.

Besides from establishing our  naming convention, the class above extends the base controller class from our core directory, and this class will also inherit the parents constructor. Mainly, the instantiation of the base model and view classes. Remember in the earlier part of this tutorial. The constructor of our base controller looks like this

 public function __construct(){
 $this->model = Ini_object::instance('ModelClass');

$this->view = Ini_object::instance('View');


 } 

Second is the method in our class called private function AboutContent, again we can easily noticed that even the naming of our method within the class gives us the cue of its function. In this particular class, the method AboutContent is going to deliver the content of this page. This content could be from database or from just a simple array of text strings. The visibility of this method is set to private, because if we are to use database as the prime source of our content, then we don't have to make an adjustments, it is already set-up as it should.

Third method is the fulfillment of the agreement between the parent class and all of its child classes. Remember in our core controller file, we declared  abstract function index();   by declaring function index() as abstract, all of the child class must fulfill this or must have a function called index().

Noticed that the method index() assigned the output of the aboutcontent method? This is not just a simple assignment though, if we can recall what we just did in previous part, we incorporated Smarty template engine. We will be writing the ViewClass.php to process and pass the output to our template file.

I hope you are understanding concept here, because if you will be venturing in a much bigger framework like CI or Kohana, you will be using similar approach in writing the application's controller. You will see more of this in CI and Kohana tutorials.

Let's move on..

Filename: CategoriesController.php
<?php

/*
   * Copyright Lorenzo D. Alipio 
   * This file is for demonstration purposes only and NOT authorize for distribution.
   * NO License will be granted for any purposes NON-profit or for profit.
   * However, the instance of smarty within the constructor of which this class instantiated is covered
   * by GNU license.
   *
   * filename: application/ViewClass.php
   * Update Date: 8-20-2013
   * Previous Version: 1.4
   * CategoriesController.php
*/

class CategoriesController extends Controller{

public function __construct(){
  parent::__construct();
 
 }

 public function index(){
 
  $cat = array(
'Charice','The Beatles','Elvis Presley', 'Nora Jones', 'James Brown','Rolling Stones','Bob Dylan','Chuck Berry','The Who','Led Zeppelin','Stevie Wonder','Jimi Hendrix','Ray Charles','The Beach Boys','Pink Floyd','Aretha Franklin','Little Richard','Marvin Gaye','Bruce Springsteen','David Bowie','Fats Domino','Black Sabbath','Queen','Buddy Holly','Bob Marley','Sam Cooke','Elton John','Neil Young','U2','Run-D.M.C.','Bo Diddley','Jerry Lee Lewis','B.B. King','Sly & The Family Stone','The Clash','Prince','The Grateful Dead','The Velvet Underground','Nirvana','Michael Jackson','The Supremes','The Temptations','Madonna','Public Enemy','The Kinks','Otis Redding','The Everly Brothers','Van Halen','Elvis Costello','Simon & Garfunkel','Cream','Frank Zappa','Roy Orbison','Eric Clapton','George Clinton & Parliament/Funkadelic','The Allman Brothers Band','Janis Joplin','The Ramones','Crosby, Stills, & Nash & Young','Fleetwood Mac','AC+DC','The Byrds','Joni Mitchell','The Eagles','Smokey Robinson & The Miracles','R.E.M.','Creedence Clearwater Revival','Johnny Cash','Van Morrison','Aerosmith','Curtis Mayfield & The Impressions','The Drifters','The Police','Metallica','Pearl Jam','Deep Purple','Bill Haley & His Comets','The Band','Santana','Yes','Jefferson Airplane','King Crimson','Al Green','The Isley Brothers','The Moody Blues','The Sex Pistols','N.W.A','Talking Heads','Tom Petty & The Heartbreakers','Billy Joel','The Bee Gees','The Yardbirds','The Four Tops','Radiohead','Patti Smith','Guns N Roses','Chicago','Rush','Bob Seger & The Silver Bullet Band','Rick Nelson','Earth Wind & Fire'
); sort($cat);
 
  $content = array(
     
     'sitepath'=>SITEPATH,
     'categoryHeader' => 'Music Video Categories',
     'cat'  => $cat
  );

  
  return $this->view->set_content($content,'categories.tpl');
 
 }
 
 }



The CategoriesController above is pretty explanatory, similar to the AboutController.php it is also following our established naming convention. I could not think of anything that we can use as category for our application. So, I figured maybe we can use all the musicians and bands of Rock n' Roll. I hope you don't mind for the sake of learning. Yes, you are feel free to change them after mastering this subject matter. For now, just leave it like that. You will have plenty of time experimenting it for your own application. I honestly believe music is universal so this will not create some issues ( I keeping my finger cross).

Disclaimer! If you are the owner of any copyrighted materials from youtube, or you are the band, or the performer, or the singer, or the artist/s, and is/are included in the random categories, I picked up from youtube, and for any reason you want your name or band remove from the list, please let me know and I will gladly remove it from the list. While you are already crusading for removal requests, please do it on youtube also, So that there will be no search results of your Name or Band on Youtube search API. All copyrights, trademarks, service-marks and everything in between  belongs to its rightful owner.


I apologize for a lengthy disclaimer. We are programmers and not lawyers, so let's move on to the next file. If you have any suggestions on what category should be use, please let me know. As long as we can utilize pagination for the result.

Filename:  IndexController.php
<?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.
* 
* IndexController.php
*/


class IndexController extends Controller{

public function __construct(){
  parent::__construct();
 
 }

 public function index(){
  $content = array(
     
     'sitepath'=>SITEPATH,
     'content' =>self::article()
  );

  ## this model content is for database
   //return $this->view->set_content($this->model->Content(),'index.tpl');
  
  return $this->view->set_content($content,((TPL === 'Smarty')? 'index.tpl' : 'index.html'));
 
 }

 private function article(){
  $article =array(

   'first_p'=> 'This demo application script demonstrate the power of MVC methodologies in web development. 
    This demo application also demonstrate the implementation of the capabilities of the following:',
             'lists' => array('Smarty templating engine','Twitter Bootstrap Front-end framework,Smarty template inheritance','Youtube API version 2,Clean extensible PHP script,Pure OOP as written in Model View Controller design Pattern','Request routing to web or public directory only','Auto redirect to the index, if the page request does not exist','Pages have their own controller to better manage the content delivery','No HTML tags in the business logic pages','Written in PHP 5.5.1 > standards'),
       'more_info'=>'This template may appear to be simple in its form, but it demonstrated the advance implementation
    of Object Oriented PHP.',
        'copyright'=> 'Property of Lorenzo D. Alipio');
    
 

 return $article;
 }
 }





Filename: LatestController.php 

<?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.
* 
* LatestController.php
*/


class LatestController extends Controller {

 public $q = "most_recent";
 public $index = '1';
 public $orderby = "published";
 public $i = 48;
 public $count ='';
 function __construct() {
  
  parent::__construct();
  Use_Class::autoload(YOUTUBE);
  
 }

public function index(){

 //$object = Ini_object::instance('YoutubeVideo');
 if(isset($_GET['q'])){
 $q = $_GET['q'];
    $q = preg_replace('/[[:space:]]+/', '/', trim($q));
    $q = str_replace('/', '+', $q);
 $index = $_GET['start-index'];
 $orderby = $_GET['orderby'];
 $i = 25;
}
else{
  $q = "AC+DC";
  $index = "1";
  $orderby = "published";
  $i = 25;
}

$object = new YoutubeVideo($q,$index,$orderby,$i);
 
 $video = array(
     'count'=> $object->getCount(),
     'video'=> $object->getVideo(),
     'sitepath'=>SITEPATH,
     'cat' => $q,
     'pagination'=>$object->pagenate('latest.php')
  );
 
 return $this->view->set_content($video,'latest.tpl');
 
}


}  




This conclude part 6A.. we will be creating the remaining controller files in part 6B.

Thursday, September 12, 2013

Creating A Simple PHP MVC Framework Part Five, Integrating Twitter Bootstrap with Smarty (smarty version)

Written by: Lorenzo D. Alipio (PHP open source developer)

We are on part five of  "Creating A Simple PHP MVC Framework (smarty version)" tutorial series. In this series, we will be integrating the Twitter Bootstrap front-end framework.

Download the twitter bootstrap here. Unzipped the file and move them in our project directory as shown by the directory diagram below.

+web
   +themes
        +default
            + css
            + font
            + ico
            + img
            + js

Inside the default directory create these 2 template files for the smarty. main.tpl will be the parent template and index.tpl for our first application template.

+web
   +themes
        +default
         |    + css
         |    + font
         |   + ico
         |   + img
         |   + js
         main.tpl
         index.tpl
     

This concludes our integration of twitter bootstrap with smarty. On the next part, we will create our very first application.

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

 Written by Lorenzo D. Alipio (open source developer) 


In previous tutorial (part three), we managed to create crucial files for our simple MVC framework. In this series (part four), we will be creating the core files of our application. These core files will be base controller, base model  classes. For clarification, we will not be creating a base view class. The reason is that the view will be utilizing the smarty and there is no need to create an abstract method for it.

In part one, our projectcreator.php generated our base file structures as shown below.

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

Inside the mvcproject directory, create a new directory called vendor, and then create these additional directories and files.

        vendor/core
        vendor/core/controller/Controller.php
        vendor/core/model/Model.php
        vendor/core/view/View.php
        vendor/smarty/smarty
        vendor/modules/

our mvcproject directory should now look like this

htdocs
    + mvcproject
          + application
           |     + controller
           |     + model
           |     + view
           +temp
                +vendor
                 |    +core
                 |     |   +controller
                 |     |    |  Controller.php
                 |     |   +Model
                 |     |   |    Model.php
                 |     |   +View
                 |     |   |     View.php
                 |    +modules
                 |    +smarty
                 |    |     +smarty 
           +web
           |    +themes
           |         +default
           |         +themes_compile
           |         +themes_configs
           composer.json *for later
           smarty.zip *if connected to the Internet

If you already downloaded the smarty zip file, unzipped the file and then move these files to vendor/smarty/smarty directory.

          +smarty
              +smarty
                   +plugins
                    +Smarty_info
                     +sysplugins
               | debug.tpl
               | Smarty.class.php
               | SmartyBC.class.php

Let's create our base controller file.

filename: vendor/core/controller/controller.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.
 * 
 * Controller.php
 * namespace application\controller\;
*/



Abstract Class Controller {

/*
 *
 * @model use model
 * @view use view
 *
 */
protected $model;
protected $view;

function __construct() {
        
  $this->model = Ini_object::instance('ModelClass');
  $this->view = Ini_object::instance('View');
}

/**
 * set contract between main controller and the application controllers. Must have
 */
abstract function index();
}


?>

We create our base model class.
filename: vendor/core/model/BaseModel.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.
* 
* BaseModel.php
*/
//Use_Class::autoload(PDO);

Abstract Class BaseModel{

public function __construct(){}

Abstract function Content();
 
}
?>

I commented the PDO class, because it is not included in this tutorial. However, database directory can be added inside the vendor directory, and then save the pdo class there, and then just define it as a constant in the bootstrap.php

This concludes the part four of this tutorial series. For part five, we will be integrating the twitter Bootstrap front-end framework with our simple PHP MVC Framework. Stand by its coming soon..

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

  Written by: Lorenzo D. Alipio  

In part two, we utilized the .htaccess for routing page requests to the web directory. In this series (part three), we will be creating bootstrap, autoloader, singleton instantiator or objects initialization class.

filename: /application/Bootstrap.php

<?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.
* 
* Bootstrap.php
*/

if(!isset($_SESSION)){session_start();}
define('TPL','Smarty');
/*
*
* file constants definition file or bootstrap
*
*/
define( 'SITEPATH', $_SERVER['SERVER_NAME'] . str_replace($_SERVER['DOCUMENT_ROOT'], '', dirname($_SERVER['SCRIPT_FILENAME'])) .'/');

define ('EXT', '.php');
define ('DS', DIRECTORY_SEPARATOR);
define ('ROOT',(dirname(__DIR__)));
define ('TEMP',ROOT.DS .'temp'. DS );
define ('BASE_CONTROLLER', ROOT .'\vendor\core\controller_Controller');
define ('VENDOR', ROOT .'/vendor/');

/*
*Define Base model for the application
*@BASE holds database connection e.g. PDO, MYSQLI
*@MODEL application model e.g. IndexModel, YoutubeModel, the same convention as the controllers
*/

define ('BASE_MODEL',ROOT .'\vendor\core\model_Model');
define ('MODEL',ROOT .'\application\model_ModelClass');
define ('VIEW', ROOT .'\application\view_ViewClass');

/* libraries for the application */

define ('LIBS', ROOT.DS .'vendor\applib'. DS);
define ('TPL_ENG', LIBS .'template_engine'. DS);
define ('SMARTY_LOAD', LIBS .'\template_engine\smarty_Smarty.class');

/* Template engine configuration and directories */

## define public directory, accessable only to users
define ('WEB_DIR', ROOT. DS .'web'.DS);
## Theme Directory
                define( 'THEME_DIR', WEB_DIR .'themes'. DS );
                define( 'THEME_COMPILE', THEME_DIR .'themes_compile');
                define( 'THEME_CACHE', TEMP .'theme_cache'. DS);
                define( 'THEME_CONFIG', THEME_DIR .'theme_configs');
                define( 'THEME' , THEME_DIR .'green'. DS );
               

The function of the bootstrap.php above is to keep all of the files in our application. This is the page where we  define our constants. I am planning to write another tutorial similar to this, but it will be more advance than this. It will beutilizing the composer autoloader, and symfony class loader. Since this article is entitled as "simple MVC", I need to stay focus on that purpose.

Next, we will need to use some form of autoloader that is PSR-0 compliant. Since, we are creating a "Simple MVC", we will utilize fig-standards equivalent example for simplification. Also, we will be using simple singleton to load our classes.

 filename: /application/AutoLoad.php

<?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.
* 
* AutoLoad.php
*/

require_once ('Bootstrap.file.php');


class Use_Class{

    /*
     *  @autoload autoload class file.
     *  
     *  @param [in] $className class file constant name
     *  @return require_once the file
     */
public static function autoload($className)
{
  
    $className = ltrim($className, '\\');
    $fileName  = '';
    $namespace = '';
    if ($lastNsPos = strrpos($className, '\\')) {
        $namespace = substr($className, 0, $lastNsPos);
        $className = substr($className, $lastNsPos + 1);
        $fileName  = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
    }
    $fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
    

    require_once $fileName;
}
/*
*@loadController 
*@controller takes pathinfo
*@return PagecontrollerController or default IndexController
*/
public static function loadController($controller,$array=array()){
    
return((is_array($array) && ((!empty($controller) || ($controller != null) )))? array('\application\controller_'.ucfirst($controller).'Controller' , array_search($controller, $array)) : array('\application\controller_IndexController' ,'IndexController'));

}
public static function useFile($file){
    include_once($file);
}
}

/*
*
*@ini_Object initialize objects by singleton
*return objects
*/
final class Ini_object{
 
    /**
     * Maintains collection of instantiated classes
     */
    private static $instances = array();
    
    /**
     * Overload constructor
     */
    private function __construct(){}
    
    /**
     * Manages instantiation of classes
     * 
     * @param $class
     * 
     * @return self instance of the class
     */
    public static function instance($class)
    {        
        //instantiate class as necessary
        self::create($class);    
        
        //return instance
        return self::$instances[$class];
    }
    
    /**
     * Creates the instances
     * 
     * @param $class
     * 
     * @return none
     */
    private static function create($class)
    {
        //check if an instance of requested class exists
        if (!array_key_exists($class , self::$instances))
        {
            self::$instances[$class] = new $class;
        }
    }
}

/*
*@auto load base controller model, view and smarty
*/
Use_Class::autoload(BASE_CONTROLLER);
/*
*@auto load application model.. this is not the base model
*@auto load application view .. this is not the base view class
*/
Use_Class::autoload(MODEL);
Use_Class::autoload(VIEW);
Use_Class::autoload(SMARTY_LOAD);


The autoload.php above contains two classes, the first one is the Use_Class() class and the second is the Ini_Object which will serve the instances of a class as requested throughout our application. Below the page are instances of the base controller, application model, application view, and the smarty object. Later, we will be installing the Smarty template engine. Let's take care of the crucial files first, then we half-step back to make sure the smarty template files are unzipped into the proper directory.

Once again this post is getting really long, I must conclude this series and continue to build our application core files in part four of the series.

Wednesday, September 11, 2013

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

 Written by: Lorenzo D. Alipio  

This is part two of "Creating A Simple PHP MVC Framework (smarty version)" series. In part one, we were able to create our needed project directories. 

Htaccess file.
We need to create two .htaccess files. One for the project directory and one for web directory. Copy and paste codes below and save it as .htaccess inside the  mvcproject directory.

filename: mvcproject/.htaccess

<IfModule mod_rewrite.c>

    RewriteEngine on

    RewriteRule ^$  web/   [L]

    RewriteRule (.*) web/$1 [L]

 </IfModule>

the codes above will redirect all request to the web directory of our application, and there will no contents that can be accessed by the public.

Create another .htaccess file and save it inside the web directory.

filename: mvcproject/web/.htaccess

<IfModule mod_rewrite.c>

RewriteEngine On

RewriteCond $1 !\.(gif|jpg|png|ico|css|js|swf|wav|mp3|less|cur) [OR]

RewriteCond %{REQUEST_URI} ^/web/.*\.css$

RewriteCond %{REQUEST_FILENAME} !-f

RewriteCond %{REQUEST_FILENAME} !-d

 

RewriteRule ^(.*)$ index.php?url=$1 [L,QSA]

</IfModule>


We need to test if these .htaccess are working as intended. Create a php file called index.php, and save it to the root directory of out application.

<?php

echo 'Hello from the root index.php';

?>

Create another index.php file and save it in the web directory.       
<?php

echo 'Hello from the Web directory index.php';

?>

Direct your browser to http://localhost/mvcproject/. If everything is well, we should be reading
"Hello from the Web directory index.php".

This concludes the part two of creating our PHP MVC framework tutorial series. Next will be part three, and we will be creating bootstrap and autoloader files. See you next time and thank you for reading. 

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 ....