SlideShare uma empresa Scribd logo
1 de 42
How to learn to build
your own PHP framework
    Bridging the gap between PHP, OOP and Software Architecture

                             Pham Cong Dinh (a.k.a pcdinh)
                                      Software Developer


                                                  Hanoi PHP Day - December 2008
                                                                  Hanoi - Vietnam




                         Copyright © Pham Cong Dinh. All rights un-reserved.
How to develop your own framework                        Introduction



Introduction
   A foundation member of JavaVietnam since 2003
    (http://www.javavietnam.org)
   A foundation member of PHPVietnam Discussion Group since 2004
    (http://groups.google.com/group/phpvietnam)
   Lead web developer with World’Vest Base Inc.
   Java is my first love since 1999
   PHP is my real lover since 2003. I love the way PHP community
    works
   Sometimes I works on Python, Ruby, Erlang
   I am a strong believer in dynamic programming languages,
    JavaScript, web standards, convergence of web as a platform and
    Outsourcing 2.0
   I spent 2 years to play with my framework named Pone (PHP One)

                                                   2
How to develop your own framework                                Introduction



Objectives
   Where is PHP now? It is changing.
       Enterprise oriented: which is driven by Yahoo, Facebook, Zend,
       Sun/MySQL, Oracle, OmniTI … PHP is too big. It can not just be
       ignored
       Object Oriented Programming adoption
       Increased complexity of web applications
       Web vs. Adobe Air, MS Silverlight, JavaFX, Google Native Client
       Trends Will Move Applications to the Web: Consumer Innovation Setting
       the Pace, Rise of the Power Collaborator, New Economics of Scale for
       IT, Barriers to Adoption Are Falling
       Scale-out wins
   Understanding what framework designers think
   Building up shared mindsets
   Providing food for thought
                                                         3
How to develop your own framework                 Introduction



Agenda – 40 slides

   Making judgments
   Top notch frameworks and their shortcomings
   A broader view on your framework
   Lessons to learn




                                            4
How to develop your own framework


                  Making judgments

• Common wisdom: Reinventing the wheel
• Good
    –   You know it inside and out
    –   You control its pace
    –   It fits your needs. Sometimes, your need is unique
    –   It teaches you how the world around you works
    –   License: This is why GPL is sometime a bad thing
• Bad
    –   You may not as good as other ones
    –   No community
    –   No outside contributors
    –   Reinventing the square wheel
                                                             5
How to develop your own framework


              Making judgments

• To develop a framework is just like to set up a business
• Think of your limitation: time, resources, knowledge to
  build/test/document/maintain your own mental baby
• Know your team: how to train them
• Know the market: known frameworks in the market.
  Sometimes your needs are satisfied to some extent in several
  little-known frameworks
• Starts with pencil and paper: its components and how they
  interact
• Starts with API: learn how to design an API first
• You never do it right from day one

                                                             6
How to develop your own framework


              Know the market

• CakePHP shortcomings
• Zend Framework shortcomings
• Third party frameworks shortcomings




                                        7
How to develop your own framework


        Know the market - CakePHP

• Misleading terms: plugin, model…
    – Plugin: CakePHP allows you to set up a combination of controllers,
      models, and views and release them as a packaged application
• Too database centric: CakePHP naming convention is driven by table names, not
   dependency injection mechanism.

• Admin routing sucks: why do we need one-and-only backend
  for the whole application/plugin/etc…?
• Flat application structure: plugin/controller/action and no
  more.
• Global space constants


                                                                                  8
How to develop your own framework


       Know the market - CakePHP

• No elegant way to change media file (css,
  javascript, meta content) on each layout
  page, controlled by a Controller.
   <head>
      <?php echo $html->charset(); ?>
      <title>
             <?php echo $title_for_layout; ?>
      </title>
      <?php
         echo $html->css('cake.generic');
         echo $javascript->link('prototype-1.6.0.2');
         echo $scripts_for_layout;
         echo $html->meta('icon','/myapp/img/favicon.ico', array
   ('type' =>'icon'));
      ?>
   </head>


                                                                   9
How to develop your own framework


      Know the market - CakePHP

• loadModel(), loadController() are not about dependency injection
• E.x: You want to provide access to a model from a Component
  Say you have a model called FooBar in a file called foo_bar.php

  loadModel('FooBar');
  $this->FooBar = &new FooBar();
• loadModel() maybe deprecated in favor of
  App::import('Model', 'ModelName');




                                                                     10
How to develop your own framework


        Know the market - CakePHP

• beforeFilter(), afterFilter() are coupled with a certain controller
  (controller is a heavy object. It should avoid being hit too soon)
  <?php
   class AppController extends Controller {
       var $beforeFilter = array('checkAccess');

        var $components = array('Acl');

        function checkAccess(){
        }
   }
   ?>



                                                                        11
How to develop your own framework


       Know the market - CakePHP

• Reuse of view via elements with requestAction() is bad and
  expensive
   – The dispatcher is called for each call to a controller (routing,
     figures out what (Plugin)/Controller/Action is request, loops
     through all $paths->controllerPaths files, to figure out what
     Controller to load)
   – The controller is set up again
• Behavior: controllerActAsModel
• Controller is an interface to another tier
• Controller is not designed to provide data for internal components
• Cache unfriendly


                                                                        12
How to develop your own framework


         Know the market - CakePHP

• Caching hits its hard time because there is no way to get
  generated view content

    <?php
    $this->element('helpbox', array("cache" => array('time'=> "+7
      days",'key'=>'unique value')));
    ?>

• What about URL-based caching, session/cookie-
  based caching, geo-based caching, date-based
  caching
    (there are a lot of things to tell about CakePHP but it is all for today)
                                                                                13
How to develop your own framework


   Know the market – Zend Framework

• Zend Framework tries to be a better PEAR
    –   Powered by a solid foundation
    –   A solid and controllable licensing (CLA)
    –   More strictly controlled development environment
    –   Enterprise-oriented class library
    –   A well-defined roadmap and versioning
• Zend Framework is a glue framework or framework-
  oriented class library




                                                           14
How to develop your own framework


   Know the market – Zend Framework

• Zend Framework is extremely big and bloated
    –   Zend Framework 1.6.2: 1261 file, 267 folders
    –   Zend_Mail: 33 files
    –   Zend_Pdf: 89 files
    –   Zend_Controller: 50 files
    –   Zend_View: 57 files
    –   Drupal includes folders: 33 files
• Zend Framework is designed most like Java frameworks
    –   Small class file
    –   Lot of classes: object graph is hard (see next)
    –   Atomic responsibility
    –   Strongly embrace design patterns
                                                          15
How to develop your own framework




                                    16
How to develop your own framework


    Know the market – Zend Framework

•   Everything is an object, even a HTML button or checkbox. The same to Java
    (see Apache Wicket, Tapestry, JBoss Seam)
     class Zend_View_Helper_FormReset extends Zend_View_Helper_FormElement
     {
         public function formReset($name = '', $value = 'Reset', $attribs = null)
         {
             $info = $this->_getInfo($name, $value, $attribs);
             extract($info); // name, value, attribs, options, listsep, disable

            // check if disabled
            $disabled = '';
            if ($disable) {
                $disabled = ' disabled="disabled"';
            }

            // get closing tag
            $endTag = '>';
            if ($this->view->doctype()->isXhtml()) {
                $endTag = ' />';
            }

             // Render button
             $xhtml = '<input type="reset"'
                    . ' name="' . $this->view->escape($name) . '"'
                    . ' id="' . $this->view->escape($id) . '"'
                    . $disabled;
      . . . . . . . . .
          }
     }                                                                              17
How to develop your own framework


   Know the market – Zend Framework

• What Zend Framework brings
    – Lot of files are loaded per request which is a bad thing for a dynamic,
      interpreted language and stateless platform like PHP
    – Much more memory usage
    – Bad thing for PHP memory management model in which memory is
      allocated in small chunks
    – Zend Framework code: There are lot of require_once() call inside an if
      statement which is bad for opcode caching mechanism
    – Zend Framework leaves shared hosting in the cold.
        • 700 sites per server are quite normal
        • No control over file system optimization
        • No control over memory
        • No control over opcode caching


                                                                                18
How to develop your own framework


   Know the market – Zend Framework

• A glue framework requires you to know every concrete
  class and how to use them in a application life cycle
• A lot of things to consider means bootstrapping is a
  mess




                                                          19
How to develop your own framework


    Know the market – Zend Framework
define('ROOT_DIR', dirname(dirname(dirname(__FILE__))));
define('APP_DIR',dirname(dirname(__FILE__)));

set_include_path('.' . PATH_SEPARATOR . APP_DIR . '/lib/' . PATH_SEPARATOR . APP_DIR .
     '/application/default/models/' . PATH_SEPARATOR . ROOT_DIR . '/shared/lib/' . PATH_SEPARATOR .
     get_include_path());
//This requires that your Zend library lies in ROOT_DIR/shared/lib/

//make classes autoload without doing require
require_once('Zend/Loader.php');
Zend_Loader::registerAutoload();

if(defined('ENV') !== TRUE) {
     define('ENV','production');    //change staging to production to go to production settings
}

$config = new Zend_Config_Xml(APP_DIR . '/config/config.xml', ENV);
Zend_Registry::set('config',$config);

//init session
$session = new Zend_Session_Namespace($config->session_name);
Zend_Registry::set('session',$session);

Zend_Db_Table::setDefaultAdapter(Zend_Db::factory(Zend_Registry::get('config')->database));

/**
 * Init the Smarty view wrapper and set smarty suffix to the view scripts.
 */
$view = new EZ_View_Smarty($config->smarty->toArray());
                                                                                                      20
How to develop your own framework


      Know the market – Zend Framework
// use the viewrenderer to keep the code DRY instantiate and add the helper in one go
$viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('ViewRenderer');
$viewRenderer->setView($view);
$viewRenderer->setViewSuffix($config->smarty->suffix);

/**
 * Set inflector for Zend_Layout
 */
$inflector = new Zend_Filter_Inflector(':script.:suffix');
$inflector->addRules(array(':script' => array('Word_CamelCaseToDash', 'StringToLower'), 'suffix'   => $config->layout->suffix));

// Initialise Zend_Layout's MVC helpers
Zend_Layout::startMvc(array('layoutPath' => ROOT_DIR.$config->layout->layoutPath,
'view' => $view,
'contentKey' => $config->layout->contentKey,
'inflector' => $inflector));

$front = Zend_Controller_Front::getInstance();

$front->setControllerDirectory(array(
    'default' => '../application/default/controllers',
    'blog'    => '../application/blog/controllers',
));

$front->throwExceptions(true);
// enable logging to default.log
$writer = new Zend_Log_Writer_Stream(APP_DIR.'/data/log/default.log');
$logger = new Zend_Log($writer);

// give easy access to the logger
Zend_Registry::set('logger', $logger);

try {
    $front->dispatch();
} catch(Exception $e) {
    echo nl2br($e->__toString());
}                                                                                                                                  21
How to develop your own framework


   Know the market – Zend Framework

• Zend Framework is different.
    – It is not a solid application framework like CakePHP, it is
      designed to be a platform on which other frameworks are built
• Technical details should be mentioned in another talk
  (enough for today)




                                                                      22
How to develop your own framework


      A broader view on your framework

• MVC Push or Pull
    – MVC Push or Passive View
  <?php
   // Load the Savant3 class file and create an instance.
   require_once 'Savant3.php';
   $tpl = new Savant3();
   // Create a title.
   $name = "Some Of My Favorite Books";
   // Generate an array of book authors and titles.
   $booklist = array(
       array(
           'author' => 'Hernando de Soto',
           'title' => 'The Mystery of Capitalism'
       ),
       array(
           'author' => 'Neal Stephenson',
           'title' => 'Cryptonomicon'
       ),
       array(
           'author' => 'Milton Friedman',
           'title' => 'Free to Choose'
       )
   );
   // Assign values to the Savant instance.
   $tpl->title = $name;
   $tpl->books = $booklist;
   // Display a template using the assigned values.
   $tpl->display('books.tpl.php');
   ?>


                                                            23
How to develop your own framework


    A broader view on your framework

• MVC Push or Pull
    – MVC Pull or so-called HMVC (see next): break a big controller
      into small ones




                                                                      24
How to develop your own framework


 A broader view on your framework




                                    25
How to develop your own framework




                                    26
How to develop your own framework


    A broader view on your framework

• MVC Push or Pull: HMVC implementation
    – Master Controller
       /**
        * Show the home page
        *
        * @link   http://www.wvbresearch.com/home/index/index
        * @name   index
        * @access public
        */
       public function indexAction()
       {
           // Attach placeholder: the name of ElementGroup
           $this->_layout->registerBody('homeIndex');

           // Set content for the response
           $this->_response->setContent($this->_layout->render('index3col'));
       }




                                                                                27
How to develop your own framework


        A broader view on your framework

• MVC Push or Pull: HMVC implementation
    – Group Controller
    class Group_HomeIndex extends Pone_View_ElementGroup
    {
        /**
         * Elements in in this group
         *
         * @var array
         */
        protected $_elementsInGroup = array(
        'homeTopNegativeEpsSurprises', 'homeTopPositiveEpsSurprises',
        'homeIntroduction', 'brokerRatingsUpgrades', 'homeAnalystEstimatesSearchBox',
        'homeResearchReportSearchBox', 'latestResearchReports'
        );

        protected $_templateFile = 'homeIndex';

        public function setup()
        {

        }
    }




                                                                                        28
How to develop your own framework


        A broader view on your framework

• MVC Push or Pull: HMVC implementation
    – Element Controller
    class Element_LatestResearchReports extends Pone_View_Element
    {
        protected $_templateFile = 'latestResearchReportsOnHome';

        /**
         * List of recent research reports
         *
         * @var Pone_DataSet
         */
        public $researchReports;

        public function setup()
        {
            $module        = Pone::getContext()->getFront()->getRequest()->getModuleName();
            $numberOfItems = 7;
            if ('home'    !== $module)
            {
                $this->_templateFile = 'latestResearchReports';
                $numberOfItems       = 10;
            }

            $dbConn                = Pone_Action_Helper_Database::getInstance()->getConnection('oracleweb', true);
            $researchReportDs      = ResearchReportDatabaseService::getInstance($dbConn);
            $this->researchReports = $researchReportDs->findRecentList($numberOfItems);
        }
    }
                                                                                                               29
How to develop your own framework


    A broader view on your framework

• MVC Push or Pull: HMVC implementation
    – Element Controller template
    <div class="featureBlockHeader">
       <h2>Latest reports</h2>
       </div>
         <div class="textBox">
           <div class="textBoxContent">
              <?php if (true === $this->researchReports->isReadable()): $iter = $this-
       >researchReports->getIterator(); ?>

                  <ul class="imgList">
                    <?php foreach ($iter as $report): ?>
                    <li><a href="research/detail/view/rpid/<?php echo $report-
       >get('report_id') ?>"><?php echo $report->get('title'); ?></a></li>
                    <?php endforeach; ?>
                  </ul>
            <?php else: echo $this->researchReports->getMessage(); endif;?>
       </div>
    </div>




                                                                                     30
How to develop your own framework


    A broader view on your framework

• IDE support
    – Code completion rocks
    – MVC Push is bad for view data documentation
    – Zend_Registry is bad for code completion
        Zend_Registry::set('logger', $logger);
    – Think of interface because implementing a way to load dynamic
      class from a variable or an array element.
    – Learn how to write DocBlock




                                                                  31
How to develop your own framework


    A broader view on your framework

• Core feature set
    – MVC framework
        • Model layer: DBO, File handling/transformation, business rules,
          workflows, search, messaging, memory, remote resource access …
    – Validation framework instead of form handling
    – Unified directory structure: model classes, controllers, views (page
      fragments, layouts), plugins, filters, custom exceptions, helpers
    – Session
    – Authentication and ACL: Abstract and extensible
        • HTTP Digest
        • Database backed
        • SAML/SSO
        • Serializable Unified Session User Object


                                                                        32
How to develop your own framework


     A broader view on your framework

• Core feature set
    – Validation framework
    class Form_Signup extends Pone_Form_Input
    {
        . . . . . .
        public function onPost()
        {
           // Email
           $emailRules       = array(
           Pone_Form_Rule::EMAIL => array('feedback' => _t('common.error.email.notvalid'))
           );
           $this->setValidationRule('email', $emailRules);

            // Email 2
            $email2Rules    = array(
            Pone_Form_Rule::STRING_EQUAL => array('feedback' => _t('common.error.reemail.not_match'),
            'reference' => 'email')
            );
            $this->setValidationRule('email2', $email2Rules);

            // password
            $passwordRules   = array(
            Pone_Form_Rule::NOT_EMPTY    => array('feedback' => _t('common.error.password.empty'))
            );
            $this->setValidationRule('password', $passwordRules);

            // password 2
            $password2Rules = array(
            Pone_Form_Rule::STRING_EQUAL => array('feedback' => _t('common.error.repassword.not_match'),
            'reference' => 'password')                                                                     33
            );
            $this->setValidationRule('password2', $password2Rules);
        }
How to develop your own framework


    A broader view on your framework

• Much more things that need to take into account
    – Behavior layer
    – Caching
        • Distributed caching
        • Local caching
    – Dependency Injection framework
    – Internationalization


    (enough for today)



                                                    34
How to develop your own framework


                         Lessons to learn

• Take your hand dirty please.
• Singleton is bad thing when dependency injection and
  unit testing are taken into consideration
    – can't replace it with an interface
    – Factory allows for both discovery and instance management of
      the service providers
    – Final classes should keep singleton objects

    $dbConn = Pone_Action_Helper_Database::getInstance()->getConnection('oracleweb',
       true);
    $researchReportDs = ResearchReportDatabaseService::getInstance($dbConn);
    $this->researchReports = $researchReportDs->findRecentList($numberOfItems);



                                                                                       35
How to develop your own framework


                      Lessons to learn

• Factory and interface make good things
    – Factory and Adapter are good for service providers

$conn = Pone_Database_ConnectionFactory::getConnection($config);
$stmt = $conn->createStatement();
$stmt->addBatch("INSERT INTO test2 VALUES (1007, 'pcdinh1007', 1)");
$stmt->addBatch("INSERT INTO test2 VALUES (1009, 'pcdinh1009', 1)");
$stmt->addBatch("INSERT INTO test2 VALUES (1010, 'pcdinh1010', 1)");
$conn->beginTransaction();
$updateCounts = $stmt->executeBatch();




                                                                       36
How to develop your own framework


                      Lessons to learn

• Fluent interface/object chaining sometimes is a bad thing
    – Law of Demeter

$module = Pone::getContext()->getFront()->getRequest()->getModuleName();




                                                                           37
How to develop your own framework


                 Lessons to learn

• Don’t think DAO or ActiveRecord, think Domain
  Respository




                                                  38
How to develop your own framework


                    Lessons to learn

• An interface between Model and Controller must be
  defined
    – Model class returns an array: bad thing. How to catch errors and
      deal with them in the view template




                                                                    39
How to develop your own framework


                                    Lessons to learn

•   Dependency Injection
     – Does all injection through the constructor
     $libBasePath = $basePath.'/libs';
     $appBasePath = $basePath.'/apps';
     Pone::executeContext(new BenchmarkContext(), $basePath, $appBasePath, $libBasePath);

     OR

     $front->setRequest(new Pone_Request(new Pone_Request_SimpleUrlParser()));

     – Use Template Method design pattern
        • Seam

            if (session_id() === '' && PHP_SAPI != 'cli')
            {
                Pone::getContext()->loadSessionUserClass();
                $started = session_start(); // PHP 5.3: returns false or true
                $this->_started = true;
            }

     – Use XML/YAML like in Spring, Symfony which is somewhat heavy in an
       interpreted language like PHP


                                                                                            40
How to develop your own framework


                Design by Interface

• Rule: Don’t call me, I will call you
• Template Method
• Convention over configuration

                        That’s end for today




                                               41
How to develop your own framework


                    Thanks you

• Any question?




                                    42

Mais conteúdo relacionado

Mais procurados

Introduction to Drupal Basics
Introduction to Drupal BasicsIntroduction to Drupal Basics
Introduction to Drupal Basics
Juha Niemi
 
Responsive Layout Frameworks for XPages Application UI
Responsive Layout Frameworks for XPages Application UIResponsive Layout Frameworks for XPages Application UI
Responsive Layout Frameworks for XPages Application UI
Chris Toohey
 
Getting started with Catalyst and extjs
Getting started with Catalyst and extjsGetting started with Catalyst and extjs
Getting started with Catalyst and extjs
Peter Edwards
 

Mais procurados (18)

Drupal - Introduction to Drupal and Web Content Management
Drupal - Introduction to Drupal and Web Content ManagementDrupal - Introduction to Drupal and Web Content Management
Drupal - Introduction to Drupal and Web Content Management
 
Introduction to Drupal Basics
Introduction to Drupal BasicsIntroduction to Drupal Basics
Introduction to Drupal Basics
 
Drupal 8 theming deep dive
Drupal 8 theming deep diveDrupal 8 theming deep dive
Drupal 8 theming deep dive
 
Installing wordpress
Installing wordpressInstalling wordpress
Installing wordpress
 
Drupal 8 - Core and API Changes
Drupal 8 - Core and API ChangesDrupal 8 - Core and API Changes
Drupal 8 - Core and API Changes
 
DB2 and PHP in Depth on IBM i
DB2 and PHP in Depth on IBM iDB2 and PHP in Depth on IBM i
DB2 and PHP in Depth on IBM i
 
JMP402 Master Class: Managed beans and XPages: Your Time Is Now
JMP402 Master Class: Managed beans and XPages: Your Time Is NowJMP402 Master Class: Managed beans and XPages: Your Time Is Now
JMP402 Master Class: Managed beans and XPages: Your Time Is Now
 
Drupal distributions - how to build them
Drupal distributions - how to build themDrupal distributions - how to build them
Drupal distributions - how to build them
 
Add-On Development: EE Expects that Every Developer will do his Duty
Add-On Development: EE Expects that Every Developer will do his DutyAdd-On Development: EE Expects that Every Developer will do his Duty
Add-On Development: EE Expects that Every Developer will do his Duty
 
Absolute Beginners Guide to Drupal
Absolute Beginners Guide to DrupalAbsolute Beginners Guide to Drupal
Absolute Beginners Guide to Drupal
 
WordPress Theme Structure
WordPress Theme StructureWordPress Theme Structure
WordPress Theme Structure
 
Building a Custom Theme in Drupal 8
Building a Custom Theme in Drupal 8Building a Custom Theme in Drupal 8
Building a Custom Theme in Drupal 8
 
Creating Responsive Drupal Sites with Zen Grids and the Zen 5 Theme
Creating Responsive Drupal Sites with Zen Grids and the Zen 5 ThemeCreating Responsive Drupal Sites with Zen Grids and the Zen 5 Theme
Creating Responsive Drupal Sites with Zen Grids and the Zen 5 Theme
 
Responsive Layout Frameworks for XPages Application UI
Responsive Layout Frameworks for XPages Application UIResponsive Layout Frameworks for XPages Application UI
Responsive Layout Frameworks for XPages Application UI
 
Git Makes Me Angry Inside
Git Makes Me Angry InsideGit Makes Me Angry Inside
Git Makes Me Angry Inside
 
Drupal 8 introduction to theming
Drupal 8  introduction to themingDrupal 8  introduction to theming
Drupal 8 introduction to theming
 
Getting started with Catalyst and extjs
Getting started with Catalyst and extjsGetting started with Catalyst and extjs
Getting started with Catalyst and extjs
 
JavaScript-Core
JavaScript-CoreJavaScript-Core
JavaScript-Core
 

Semelhante a Howtobuildyourownframework

Hanoi php day 2008 - 01.pham cong dinh - how.to.build.your.own.framework
Hanoi php day 2008 - 01.pham cong dinh - how.to.build.your.own.frameworkHanoi php day 2008 - 01.pham cong dinh - how.to.build.your.own.framework
Hanoi php day 2008 - 01.pham cong dinh - how.to.build.your.own.framework
Nguyen Duc Phu
 
BADCamp 2012 -Beginner Best Practices
BADCamp 2012 -Beginner Best PracticesBADCamp 2012 -Beginner Best Practices
BADCamp 2012 -Beginner Best Practices
meghsweet
 
Edp bootstrapping a-software_company
Edp bootstrapping a-software_companyEdp bootstrapping a-software_company
Edp bootstrapping a-software_company
Ganesh Kulkarni
 
2013 - Dustin whittle - Escalando PHP en la vida real
2013 - Dustin whittle - Escalando PHP en la vida real2013 - Dustin whittle - Escalando PHP en la vida real
2013 - Dustin whittle - Escalando PHP en la vida real
PHP Conference Argentina
 

Semelhante a Howtobuildyourownframework (20)

How to learn to build your own PHP framework
How to learn to build your own PHP frameworkHow to learn to build your own PHP framework
How to learn to build your own PHP framework
 
Hanoi php day 2008 - 01.pham cong dinh - how.to.build.your.own.framework
Hanoi php day 2008 - 01.pham cong dinh - how.to.build.your.own.frameworkHanoi php day 2008 - 01.pham cong dinh - how.to.build.your.own.framework
Hanoi php day 2008 - 01.pham cong dinh - how.to.build.your.own.framework
 
Building and managing applications fast for IBM i
Building and managing applications fast for IBM iBuilding and managing applications fast for IBM i
Building and managing applications fast for IBM i
 
green
greengreen
green
 
Ran Mizrahi - Symfony2 meets Drupal8
Ran Mizrahi - Symfony2 meets Drupal8Ran Mizrahi - Symfony2 meets Drupal8
Ran Mizrahi - Symfony2 meets Drupal8
 
BADCamp 2012 -Beginner Best Practices
BADCamp 2012 -Beginner Best PracticesBADCamp 2012 -Beginner Best Practices
BADCamp 2012 -Beginner Best Practices
 
Edp bootstrapping a-software_company
Edp bootstrapping a-software_companyEdp bootstrapping a-software_company
Edp bootstrapping a-software_company
 
Codeigniter
CodeigniterCodeigniter
Codeigniter
 
Unleashing Creative Freedom with MODX (2015-07-21 @ PHP FRL)
Unleashing Creative Freedom with MODX (2015-07-21 @ PHP FRL)Unleashing Creative Freedom with MODX (2015-07-21 @ PHP FRL)
Unleashing Creative Freedom with MODX (2015-07-21 @ PHP FRL)
 
MVC with Zend Framework
MVC with Zend FrameworkMVC with Zend Framework
MVC with Zend Framework
 
Organinzing Your PHP Projects (2010 Memphis PHP)
Organinzing Your PHP Projects (2010 Memphis PHP)Organinzing Your PHP Projects (2010 Memphis PHP)
Organinzing Your PHP Projects (2010 Memphis PHP)
 
Organizing Your PHP Projects (2010 ConFoo)
Organizing Your PHP Projects (2010 ConFoo)Organizing Your PHP Projects (2010 ConFoo)
Organizing Your PHP Projects (2010 ConFoo)
 
Technologies for startup
Technologies for startupTechnologies for startup
Technologies for startup
 
Making the Most of Modern PHP in Drupal 7
Making the Most of Modern PHP in Drupal 7Making the Most of Modern PHP in Drupal 7
Making the Most of Modern PHP in Drupal 7
 
Symfony CMF: un nuovo paradigma per la gestione dei contenuti
Symfony CMF: un nuovo paradigma per la gestione dei contenutiSymfony CMF: un nuovo paradigma per la gestione dei contenuti
Symfony CMF: un nuovo paradigma per la gestione dei contenuti
 
Symfony CMF: un nuovo paradigma per la gestione dei contenuti
Symfony CMF: un nuovo paradigma per la gestione dei contenutiSymfony CMF: un nuovo paradigma per la gestione dei contenuti
Symfony CMF: un nuovo paradigma per la gestione dei contenuti
 
2013 - Dustin whittle - Escalando PHP en la vida real
2013 - Dustin whittle - Escalando PHP en la vida real2013 - Dustin whittle - Escalando PHP en la vida real
2013 - Dustin whittle - Escalando PHP en la vida real
 
Yii, frameworks and where PHP is heading to
Yii, frameworks and where PHP is heading toYii, frameworks and where PHP is heading to
Yii, frameworks and where PHP is heading to
 
Zend Code in ZF 2.0
Zend Code in ZF 2.0Zend Code in ZF 2.0
Zend Code in ZF 2.0
 
Becoming A Php Ninja
Becoming A Php NinjaBecoming A Php Ninja
Becoming A Php Ninja
 

Mais de hazzaz

Coffee1
Coffee1Coffee1
Coffee1
hazzaz
 
Suy ngam
Suy ngamSuy ngam
Suy ngam
hazzaz
 
Tu dong dat hang tu he thong ban le lon nhat trung quoc
Tu dong dat hang tu he thong ban le lon nhat trung quocTu dong dat hang tu he thong ban le lon nhat trung quoc
Tu dong dat hang tu he thong ban le lon nhat trung quoc
hazzaz
 
how startups can benefit from launch community
how startups can benefit from launch communityhow startups can benefit from launch community
how startups can benefit from launch community
hazzaz
 
social network game
social network gamesocial network game
social network game
hazzaz
 
trung oss magento overview
trung oss magento overviewtrung oss magento overview
trung oss magento overview
hazzaz
 
su dung drupal xay dung mang xa hoi
su dung drupal xay dung mang xa hoisu dung drupal xay dung mang xa hoi
su dung drupal xay dung mang xa hoi
hazzaz
 
html5 css3 the future of web technology
html5 css3 the future of web technologyhtml5 css3 the future of web technology
html5 css3 the future of web technology
hazzaz
 
java script unit testing framework
java script unit testing frameworkjava script unit testing framework
java script unit testing framework
hazzaz
 
build your own php extension
build your own php extensionbuild your own php extension
build your own php extension
hazzaz
 
kiem tien online
kiem tien onlinekiem tien online
kiem tien online
hazzaz
 
web optimization
web optimizationweb optimization
web optimization
hazzaz
 
speed up ntvv2 by php ext module
speed up ntvv2 by php ext modulespeed up ntvv2 by php ext module
speed up ntvv2 by php ext module
hazzaz
 
zingmepracticeforbuildingscalablewebsitewithphp
zingmepracticeforbuildingscalablewebsitewithphpzingmepracticeforbuildingscalablewebsitewithphp
zingmepracticeforbuildingscalablewebsitewithphp
hazzaz
 
mysql optimization
mysql optimizationmysql optimization
mysql optimization
hazzaz
 
EAV in Magento
EAV in MagentoEAV in Magento
EAV in Magento
hazzaz
 
css_trends
css_trendscss_trends
css_trends
hazzaz
 
Phan mem tu do nguon mo
Phan mem tu do nguon moPhan mem tu do nguon mo
Phan mem tu do nguon mo
hazzaz
 

Mais de hazzaz (20)

Coffee1
Coffee1Coffee1
Coffee1
 
Suy ngam
Suy ngamSuy ngam
Suy ngam
 
Tu dong dat hang tu he thong ban le lon nhat trung quoc
Tu dong dat hang tu he thong ban le lon nhat trung quocTu dong dat hang tu he thong ban le lon nhat trung quoc
Tu dong dat hang tu he thong ban le lon nhat trung quoc
 
how startups can benefit from launch community
how startups can benefit from launch communityhow startups can benefit from launch community
how startups can benefit from launch community
 
social network game
social network gamesocial network game
social network game
 
trung oss magento overview
trung oss magento overviewtrung oss magento overview
trung oss magento overview
 
su dung drupal xay dung mang xa hoi
su dung drupal xay dung mang xa hoisu dung drupal xay dung mang xa hoi
su dung drupal xay dung mang xa hoi
 
html5 css3 the future of web technology
html5 css3 the future of web technologyhtml5 css3 the future of web technology
html5 css3 the future of web technology
 
java script unit testing framework
java script unit testing frameworkjava script unit testing framework
java script unit testing framework
 
build your own php extension
build your own php extensionbuild your own php extension
build your own php extension
 
kiem tien online
kiem tien onlinekiem tien online
kiem tien online
 
web optimization
web optimizationweb optimization
web optimization
 
speed up ntvv2 by php ext module
speed up ntvv2 by php ext modulespeed up ntvv2 by php ext module
speed up ntvv2 by php ext module
 
zingmepracticeforbuildingscalablewebsitewithphp
zingmepracticeforbuildingscalablewebsitewithphpzingmepracticeforbuildingscalablewebsitewithphp
zingmepracticeforbuildingscalablewebsitewithphp
 
mysql optimization
mysql optimizationmysql optimization
mysql optimization
 
EAV in Magento
EAV in MagentoEAV in Magento
EAV in Magento
 
Albus
AlbusAlbus
Albus
 
css_trends
css_trendscss_trends
css_trends
 
Cloud
CloudCloud
Cloud
 
Phan mem tu do nguon mo
Phan mem tu do nguon moPhan mem tu do nguon mo
Phan mem tu do nguon mo
 

Último

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Último (20)

GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 

Howtobuildyourownframework

  • 1. How to learn to build your own PHP framework Bridging the gap between PHP, OOP and Software Architecture Pham Cong Dinh (a.k.a pcdinh) Software Developer Hanoi PHP Day - December 2008 Hanoi - Vietnam Copyright © Pham Cong Dinh. All rights un-reserved.
  • 2. How to develop your own framework Introduction Introduction  A foundation member of JavaVietnam since 2003 (http://www.javavietnam.org)  A foundation member of PHPVietnam Discussion Group since 2004 (http://groups.google.com/group/phpvietnam)  Lead web developer with World’Vest Base Inc.  Java is my first love since 1999  PHP is my real lover since 2003. I love the way PHP community works  Sometimes I works on Python, Ruby, Erlang  I am a strong believer in dynamic programming languages, JavaScript, web standards, convergence of web as a platform and Outsourcing 2.0  I spent 2 years to play with my framework named Pone (PHP One) 2
  • 3. How to develop your own framework Introduction Objectives  Where is PHP now? It is changing. Enterprise oriented: which is driven by Yahoo, Facebook, Zend, Sun/MySQL, Oracle, OmniTI … PHP is too big. It can not just be ignored Object Oriented Programming adoption Increased complexity of web applications Web vs. Adobe Air, MS Silverlight, JavaFX, Google Native Client Trends Will Move Applications to the Web: Consumer Innovation Setting the Pace, Rise of the Power Collaborator, New Economics of Scale for IT, Barriers to Adoption Are Falling Scale-out wins  Understanding what framework designers think  Building up shared mindsets  Providing food for thought 3
  • 4. How to develop your own framework Introduction Agenda – 40 slides  Making judgments  Top notch frameworks and their shortcomings  A broader view on your framework  Lessons to learn 4
  • 5. How to develop your own framework Making judgments • Common wisdom: Reinventing the wheel • Good – You know it inside and out – You control its pace – It fits your needs. Sometimes, your need is unique – It teaches you how the world around you works – License: This is why GPL is sometime a bad thing • Bad – You may not as good as other ones – No community – No outside contributors – Reinventing the square wheel 5
  • 6. How to develop your own framework Making judgments • To develop a framework is just like to set up a business • Think of your limitation: time, resources, knowledge to build/test/document/maintain your own mental baby • Know your team: how to train them • Know the market: known frameworks in the market. Sometimes your needs are satisfied to some extent in several little-known frameworks • Starts with pencil and paper: its components and how they interact • Starts with API: learn how to design an API first • You never do it right from day one 6
  • 7. How to develop your own framework Know the market • CakePHP shortcomings • Zend Framework shortcomings • Third party frameworks shortcomings 7
  • 8. How to develop your own framework Know the market - CakePHP • Misleading terms: plugin, model… – Plugin: CakePHP allows you to set up a combination of controllers, models, and views and release them as a packaged application • Too database centric: CakePHP naming convention is driven by table names, not dependency injection mechanism. • Admin routing sucks: why do we need one-and-only backend for the whole application/plugin/etc…? • Flat application structure: plugin/controller/action and no more. • Global space constants 8
  • 9. How to develop your own framework Know the market - CakePHP • No elegant way to change media file (css, javascript, meta content) on each layout page, controlled by a Controller. <head> <?php echo $html->charset(); ?> <title> <?php echo $title_for_layout; ?> </title> <?php echo $html->css('cake.generic'); echo $javascript->link('prototype-1.6.0.2'); echo $scripts_for_layout; echo $html->meta('icon','/myapp/img/favicon.ico', array ('type' =>'icon')); ?> </head> 9
  • 10. How to develop your own framework Know the market - CakePHP • loadModel(), loadController() are not about dependency injection • E.x: You want to provide access to a model from a Component Say you have a model called FooBar in a file called foo_bar.php loadModel('FooBar'); $this->FooBar = &new FooBar(); • loadModel() maybe deprecated in favor of App::import('Model', 'ModelName'); 10
  • 11. How to develop your own framework Know the market - CakePHP • beforeFilter(), afterFilter() are coupled with a certain controller (controller is a heavy object. It should avoid being hit too soon) <?php class AppController extends Controller { var $beforeFilter = array('checkAccess'); var $components = array('Acl'); function checkAccess(){ } } ?> 11
  • 12. How to develop your own framework Know the market - CakePHP • Reuse of view via elements with requestAction() is bad and expensive – The dispatcher is called for each call to a controller (routing, figures out what (Plugin)/Controller/Action is request, loops through all $paths->controllerPaths files, to figure out what Controller to load) – The controller is set up again • Behavior: controllerActAsModel • Controller is an interface to another tier • Controller is not designed to provide data for internal components • Cache unfriendly 12
  • 13. How to develop your own framework Know the market - CakePHP • Caching hits its hard time because there is no way to get generated view content <?php $this->element('helpbox', array("cache" => array('time'=> "+7 days",'key'=>'unique value'))); ?> • What about URL-based caching, session/cookie- based caching, geo-based caching, date-based caching (there are a lot of things to tell about CakePHP but it is all for today) 13
  • 14. How to develop your own framework Know the market – Zend Framework • Zend Framework tries to be a better PEAR – Powered by a solid foundation – A solid and controllable licensing (CLA) – More strictly controlled development environment – Enterprise-oriented class library – A well-defined roadmap and versioning • Zend Framework is a glue framework or framework- oriented class library 14
  • 15. How to develop your own framework Know the market – Zend Framework • Zend Framework is extremely big and bloated – Zend Framework 1.6.2: 1261 file, 267 folders – Zend_Mail: 33 files – Zend_Pdf: 89 files – Zend_Controller: 50 files – Zend_View: 57 files – Drupal includes folders: 33 files • Zend Framework is designed most like Java frameworks – Small class file – Lot of classes: object graph is hard (see next) – Atomic responsibility – Strongly embrace design patterns 15
  • 16. How to develop your own framework 16
  • 17. How to develop your own framework Know the market – Zend Framework • Everything is an object, even a HTML button or checkbox. The same to Java (see Apache Wicket, Tapestry, JBoss Seam) class Zend_View_Helper_FormReset extends Zend_View_Helper_FormElement { public function formReset($name = '', $value = 'Reset', $attribs = null) { $info = $this->_getInfo($name, $value, $attribs); extract($info); // name, value, attribs, options, listsep, disable // check if disabled $disabled = ''; if ($disable) { $disabled = ' disabled="disabled"'; } // get closing tag $endTag = '>'; if ($this->view->doctype()->isXhtml()) { $endTag = ' />'; } // Render button $xhtml = '<input type="reset"' . ' name="' . $this->view->escape($name) . '"' . ' id="' . $this->view->escape($id) . '"' . $disabled; . . . . . . . . . } } 17
  • 18. How to develop your own framework Know the market – Zend Framework • What Zend Framework brings – Lot of files are loaded per request which is a bad thing for a dynamic, interpreted language and stateless platform like PHP – Much more memory usage – Bad thing for PHP memory management model in which memory is allocated in small chunks – Zend Framework code: There are lot of require_once() call inside an if statement which is bad for opcode caching mechanism – Zend Framework leaves shared hosting in the cold. • 700 sites per server are quite normal • No control over file system optimization • No control over memory • No control over opcode caching 18
  • 19. How to develop your own framework Know the market – Zend Framework • A glue framework requires you to know every concrete class and how to use them in a application life cycle • A lot of things to consider means bootstrapping is a mess 19
  • 20. How to develop your own framework Know the market – Zend Framework define('ROOT_DIR', dirname(dirname(dirname(__FILE__)))); define('APP_DIR',dirname(dirname(__FILE__))); set_include_path('.' . PATH_SEPARATOR . APP_DIR . '/lib/' . PATH_SEPARATOR . APP_DIR . '/application/default/models/' . PATH_SEPARATOR . ROOT_DIR . '/shared/lib/' . PATH_SEPARATOR . get_include_path()); //This requires that your Zend library lies in ROOT_DIR/shared/lib/ //make classes autoload without doing require require_once('Zend/Loader.php'); Zend_Loader::registerAutoload(); if(defined('ENV') !== TRUE) { define('ENV','production'); //change staging to production to go to production settings } $config = new Zend_Config_Xml(APP_DIR . '/config/config.xml', ENV); Zend_Registry::set('config',$config); //init session $session = new Zend_Session_Namespace($config->session_name); Zend_Registry::set('session',$session); Zend_Db_Table::setDefaultAdapter(Zend_Db::factory(Zend_Registry::get('config')->database)); /** * Init the Smarty view wrapper and set smarty suffix to the view scripts. */ $view = new EZ_View_Smarty($config->smarty->toArray()); 20
  • 21. How to develop your own framework Know the market – Zend Framework // use the viewrenderer to keep the code DRY instantiate and add the helper in one go $viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('ViewRenderer'); $viewRenderer->setView($view); $viewRenderer->setViewSuffix($config->smarty->suffix); /** * Set inflector for Zend_Layout */ $inflector = new Zend_Filter_Inflector(':script.:suffix'); $inflector->addRules(array(':script' => array('Word_CamelCaseToDash', 'StringToLower'), 'suffix' => $config->layout->suffix)); // Initialise Zend_Layout's MVC helpers Zend_Layout::startMvc(array('layoutPath' => ROOT_DIR.$config->layout->layoutPath, 'view' => $view, 'contentKey' => $config->layout->contentKey, 'inflector' => $inflector)); $front = Zend_Controller_Front::getInstance(); $front->setControllerDirectory(array( 'default' => '../application/default/controllers', 'blog' => '../application/blog/controllers', )); $front->throwExceptions(true); // enable logging to default.log $writer = new Zend_Log_Writer_Stream(APP_DIR.'/data/log/default.log'); $logger = new Zend_Log($writer); // give easy access to the logger Zend_Registry::set('logger', $logger); try { $front->dispatch(); } catch(Exception $e) { echo nl2br($e->__toString()); } 21
  • 22. How to develop your own framework Know the market – Zend Framework • Zend Framework is different. – It is not a solid application framework like CakePHP, it is designed to be a platform on which other frameworks are built • Technical details should be mentioned in another talk (enough for today) 22
  • 23. How to develop your own framework A broader view on your framework • MVC Push or Pull – MVC Push or Passive View <?php // Load the Savant3 class file and create an instance. require_once 'Savant3.php'; $tpl = new Savant3(); // Create a title. $name = "Some Of My Favorite Books"; // Generate an array of book authors and titles. $booklist = array( array( 'author' => 'Hernando de Soto', 'title' => 'The Mystery of Capitalism' ), array( 'author' => 'Neal Stephenson', 'title' => 'Cryptonomicon' ), array( 'author' => 'Milton Friedman', 'title' => 'Free to Choose' ) ); // Assign values to the Savant instance. $tpl->title = $name; $tpl->books = $booklist; // Display a template using the assigned values. $tpl->display('books.tpl.php'); ?> 23
  • 24. How to develop your own framework A broader view on your framework • MVC Push or Pull – MVC Pull or so-called HMVC (see next): break a big controller into small ones 24
  • 25. How to develop your own framework A broader view on your framework 25
  • 26. How to develop your own framework 26
  • 27. How to develop your own framework A broader view on your framework • MVC Push or Pull: HMVC implementation – Master Controller /** * Show the home page * * @link http://www.wvbresearch.com/home/index/index * @name index * @access public */ public function indexAction() { // Attach placeholder: the name of ElementGroup $this->_layout->registerBody('homeIndex'); // Set content for the response $this->_response->setContent($this->_layout->render('index3col')); } 27
  • 28. How to develop your own framework A broader view on your framework • MVC Push or Pull: HMVC implementation – Group Controller class Group_HomeIndex extends Pone_View_ElementGroup { /** * Elements in in this group * * @var array */ protected $_elementsInGroup = array( 'homeTopNegativeEpsSurprises', 'homeTopPositiveEpsSurprises', 'homeIntroduction', 'brokerRatingsUpgrades', 'homeAnalystEstimatesSearchBox', 'homeResearchReportSearchBox', 'latestResearchReports' ); protected $_templateFile = 'homeIndex'; public function setup() { } } 28
  • 29. How to develop your own framework A broader view on your framework • MVC Push or Pull: HMVC implementation – Element Controller class Element_LatestResearchReports extends Pone_View_Element { protected $_templateFile = 'latestResearchReportsOnHome'; /** * List of recent research reports * * @var Pone_DataSet */ public $researchReports; public function setup() { $module = Pone::getContext()->getFront()->getRequest()->getModuleName(); $numberOfItems = 7; if ('home' !== $module) { $this->_templateFile = 'latestResearchReports'; $numberOfItems = 10; } $dbConn = Pone_Action_Helper_Database::getInstance()->getConnection('oracleweb', true); $researchReportDs = ResearchReportDatabaseService::getInstance($dbConn); $this->researchReports = $researchReportDs->findRecentList($numberOfItems); } } 29
  • 30. How to develop your own framework A broader view on your framework • MVC Push or Pull: HMVC implementation – Element Controller template <div class="featureBlockHeader"> <h2>Latest reports</h2> </div> <div class="textBox"> <div class="textBoxContent"> <?php if (true === $this->researchReports->isReadable()): $iter = $this- >researchReports->getIterator(); ?> <ul class="imgList"> <?php foreach ($iter as $report): ?> <li><a href="research/detail/view/rpid/<?php echo $report- >get('report_id') ?>"><?php echo $report->get('title'); ?></a></li> <?php endforeach; ?> </ul> <?php else: echo $this->researchReports->getMessage(); endif;?> </div> </div> 30
  • 31. How to develop your own framework A broader view on your framework • IDE support – Code completion rocks – MVC Push is bad for view data documentation – Zend_Registry is bad for code completion Zend_Registry::set('logger', $logger); – Think of interface because implementing a way to load dynamic class from a variable or an array element. – Learn how to write DocBlock 31
  • 32. How to develop your own framework A broader view on your framework • Core feature set – MVC framework • Model layer: DBO, File handling/transformation, business rules, workflows, search, messaging, memory, remote resource access … – Validation framework instead of form handling – Unified directory structure: model classes, controllers, views (page fragments, layouts), plugins, filters, custom exceptions, helpers – Session – Authentication and ACL: Abstract and extensible • HTTP Digest • Database backed • SAML/SSO • Serializable Unified Session User Object 32
  • 33. How to develop your own framework A broader view on your framework • Core feature set – Validation framework class Form_Signup extends Pone_Form_Input { . . . . . . public function onPost() { // Email $emailRules = array( Pone_Form_Rule::EMAIL => array('feedback' => _t('common.error.email.notvalid')) ); $this->setValidationRule('email', $emailRules); // Email 2 $email2Rules = array( Pone_Form_Rule::STRING_EQUAL => array('feedback' => _t('common.error.reemail.not_match'), 'reference' => 'email') ); $this->setValidationRule('email2', $email2Rules); // password $passwordRules = array( Pone_Form_Rule::NOT_EMPTY => array('feedback' => _t('common.error.password.empty')) ); $this->setValidationRule('password', $passwordRules); // password 2 $password2Rules = array( Pone_Form_Rule::STRING_EQUAL => array('feedback' => _t('common.error.repassword.not_match'), 'reference' => 'password') 33 ); $this->setValidationRule('password2', $password2Rules); }
  • 34. How to develop your own framework A broader view on your framework • Much more things that need to take into account – Behavior layer – Caching • Distributed caching • Local caching – Dependency Injection framework – Internationalization (enough for today) 34
  • 35. How to develop your own framework Lessons to learn • Take your hand dirty please. • Singleton is bad thing when dependency injection and unit testing are taken into consideration – can't replace it with an interface – Factory allows for both discovery and instance management of the service providers – Final classes should keep singleton objects $dbConn = Pone_Action_Helper_Database::getInstance()->getConnection('oracleweb', true); $researchReportDs = ResearchReportDatabaseService::getInstance($dbConn); $this->researchReports = $researchReportDs->findRecentList($numberOfItems); 35
  • 36. How to develop your own framework Lessons to learn • Factory and interface make good things – Factory and Adapter are good for service providers $conn = Pone_Database_ConnectionFactory::getConnection($config); $stmt = $conn->createStatement(); $stmt->addBatch("INSERT INTO test2 VALUES (1007, 'pcdinh1007', 1)"); $stmt->addBatch("INSERT INTO test2 VALUES (1009, 'pcdinh1009', 1)"); $stmt->addBatch("INSERT INTO test2 VALUES (1010, 'pcdinh1010', 1)"); $conn->beginTransaction(); $updateCounts = $stmt->executeBatch(); 36
  • 37. How to develop your own framework Lessons to learn • Fluent interface/object chaining sometimes is a bad thing – Law of Demeter $module = Pone::getContext()->getFront()->getRequest()->getModuleName(); 37
  • 38. How to develop your own framework Lessons to learn • Don’t think DAO or ActiveRecord, think Domain Respository 38
  • 39. How to develop your own framework Lessons to learn • An interface between Model and Controller must be defined – Model class returns an array: bad thing. How to catch errors and deal with them in the view template 39
  • 40. How to develop your own framework Lessons to learn • Dependency Injection – Does all injection through the constructor $libBasePath = $basePath.'/libs'; $appBasePath = $basePath.'/apps'; Pone::executeContext(new BenchmarkContext(), $basePath, $appBasePath, $libBasePath); OR $front->setRequest(new Pone_Request(new Pone_Request_SimpleUrlParser())); – Use Template Method design pattern • Seam if (session_id() === '' && PHP_SAPI != 'cli') { Pone::getContext()->loadSessionUserClass(); $started = session_start(); // PHP 5.3: returns false or true $this->_started = true; } – Use XML/YAML like in Spring, Symfony which is somewhat heavy in an interpreted language like PHP 40
  • 41. How to develop your own framework Design by Interface • Rule: Don’t call me, I will call you • Template Method • Convention over configuration That’s end for today 41
  • 42. How to develop your own framework Thanks you • Any question? 42

Notas do Editor

  1. You need to think different. You can not see it in a 1999 manner. Java purist mindsets are obsolete