ÊÖ°ÑÊÖ±àдPHP¿ò¼Ü ÉîÈëÁ˽âMVCÔËÐÐÁ÷³Ì

5年以前  |  阅读数:764 次  |  编程语言:PHP 

1 ʲôÊÇMVC

MVCģʽ£¨Model-View-Controller£(C)ÊÇÈi¼þ¹¤³ÌÖеÄÒ»ÖÖÈi¼þ¼Ü¹¹Ä£Ê½£¬°ÑÈi¼þϵͳÖΪÈý¸o»u±¾²¿Ö£ºÄ£ÐÍ£¨Model£(C)¡¢ÊÓͼ£¨View£(C)ºÍ¿ØÖÆÆ÷£¨Controller£(C)¡£

PHPÖÐMVCģʽҲ³ÆWeb MVC£¬´ÓÉÏÊÀ¼Í70Äe´u½ø»¯¶øÀ´¡£MVCµÄÄ¿µÄÊÇʵÏÖÒ»ÖÖ¶¯Ì¬µÄ³ÌÐoÉe¼Æ£¬±aÓÚºoÐø¶Ô³ÌÐoµÄÐ޸ĺÍÀ(C)Õ¹¼o»¯£¬²¢ÇÒʹ³ÌÐoijһ²¿ÖµÄÖظ´ÀuÓóÉΪ¿ÉÄÜ¡£³ý ´ËÖ®Ía£¬´Ëģʽͨ¹ý¶Ô¸´ÔӶȵļo»¯£¬Ê¹³ÌÐo½a¹¹¸u¼ÓÖ±¹Û¡£Èi¼þϵͳͨ¹ý¶Ô×ÔÉi»u±¾²¿ÝÖÀeµÄͬʱ£¬Ò²¸³ÓeÁ˸÷¸o»u±¾²¿ÖÓ¦ÓеŦÄÜ¡£

MVC¸÷²¿ÖµÄÖ°ÄÜ£º
•Ä£ÐÍModel ¨C ¹ÜÀi´o²¿
ÖµÄÒµÎñÂß¼­ºÍËuÓеÄÊý¾Ý¿aÂß¼­¡£Ä£ÐÍÌa¹(C)ÁËÁ¬½ÓºÍ²Ù×÷Êý¾Ý¿aµÄ³eÏo²a¡£
•¿ØÖÆÆ÷Controller - ¸ºÔðÏiÓ¦Óû§ÇeÇo¡¢×¼±¸Êý¾Ý£¬ÒÔ¼°¾o¶¨ÈçºÎչʾÊý¾Ý¡£
•ÊÓͼView ¨C ¸ºÔðaÖȾÊý¾Ý£¬Í¨¹ýHTML*½Ê½³ÊÏÖ¸øÓû§¡£

Ò»¸oµaÐ͵ÄWeb MVCÁ÷³Ì£º
1.Controller½Ø»ñÓû§*¢³oµÄÇeÇo£»
2.Controllerµ÷ÓÃModelÍe³É״̬µÄ¶Áд²Ù×÷£»
3.Controller°ÑÊý¾Ý´«µÝ¸øView£»
4.ViewaÖȾ×iÖÕ½a¹u²¢³ÊÏ׸øÓû§¡£

*2 ΪʲôҪ×Ô¼º¿ª¢MVC¿o¼Ü**

ÍøÂçÉÏÓдoÁ¿ÓÅÐaµÄMVC¿o¼Ü¿É¹(C)ʹÓ㬱¾½Ì³Ì²¢²»ÊÇΪÁË¿ª¢Ò»¸oÈ«ÃaeµÄ¡¢ÖÕ¼«µÄMVC¿o¼Ü½a¾o½°¸£¬¶øÊǽ«Ëu¿´×÷ÊÇÒ»¸oºÜºÃµÄ´ÓÄÚ²¿Ñ§Ï°PHPµÄ»u»a£¬Ôڴ˹ý³ÌÖУ¬Äa½«Ñ§Ï°ÃaeÏo¶ÔÏo±a³ÌºÍMVCÉe¼Æģʽ£¬²¢Ñ§Ï°µ½¿ª*¢ÖеÄÒ»Ð(C)×¢ÒaÊÂÏi¡£

¸uÖØÒªµÄÊÇ£¬Äa¿ÉÒÔÍeÈ«¿ØÖÆÄaµÄ¿o¼Ü£¬²¢½«ÄaµÄÏe¨ÈÚÈeµ½Äa¿ª¢µÄ¿o¼ÜÖС£ËaÈ»²»Ò»¶¨ÊÇ×oºÃµÄ£¬µ«ÊÇÄa¿ÉÒÔ°´ÕÕÄaµÄ½Ê½È¥¿ª¢¹¦ÄܺÍÄ£¿e¡£

*3 ¿ªÊ¼¿ª¢×Ô¼ºµÄMVC¿o¼Ü**

3.1 Ŀ¼׼±¸

ÔÚ¿ªÊ¼¿ª*¢Ç°£¬ÈÃÎÒÃÇÏÈÀ´°ÑÏiÄ¿½¨Á¢ºÃ£¬¼ÙÉeÎÒÃǽ¨Á¢µÄÏiĿΪ todo£¬MVCµÄ¿o¼Ü¿ÉÒÔÃuÃuΪ FastPHP£¬ÄÇô½ÓÏÂÀ´µÄµÚÒ»²½¾ÍÊÇ°ÑĿ¼½a¹¹ÏÈÉeÖúá£

ËaÈ»ÔÚÕa¸o½Ì³ÌÖв»»aʹÓõ½ÉÏÃaeµÄËuÓеÄĿ¼£¬µ«ÊÇΪÁËÒÔºo³ÌÐoµÄ¿ÉÍØÕ¹ÐÔ£¬ÔÚÒ»¿ªÊ¼¾Í°Ñ³ÌÐoĿ¼ÉeÖúÃʹ*dz£±ØÒªµÄ¡£ÏÂÃae¾Í¾ßÌa˵˵ÿ¸oĿ¼µÄ×÷Óãº
•application ¨C Ó¦ÓôuÂe
•config ¨C ³ÌÐoÅaÖûoÊý¾Ý¿aÅaÖÃ
•fastphp - ¿o¼ÜºËÐÄĿ¼
•public ¨C ¾²Ì¬Îļþ
•runtime - ÁÙʱÊý¾ÝĿ¼
•scripts ¨C ÃuÁiÐй¤¾ß

3.2 ´uÂe¹ae*¶

ÔÚĿ¼ÉeÖúÃÒÔºo£¬ÎÒÃǽÓÏÂÀ´¾ÍÒªÀ´¹ae¶¨Ò»Ï´uÂeµÄ¹ae*¶£º
1.MySQLµÄ±iÃuÐeСд£¬È磺item£¬car
2.Ä£¿eÃu£¨Models£(C)ÐeÊ××Öĸ´oд£¬£¬²¢ÔÚÃu³ÆºoÌi¼Ó¡°Model¡±£¬È磺ItemModel£¬CarModel
3.¿ØÖÆÆ÷£¨Controllers£(C)ÐeÊ××Öĸ´oд£¬£¬²¢ÔÚÃu³ÆÖÐÌi¼Ó¡°Controller¡±£¬È磺ItemController£¬CarController
4.ÊÓͼ£¨Views£(C)²¿Êð½a¹¹Îª¡°¿ØÖÆÆ÷Ãu/ÐÐΪÃu¡±£¬È磺item/view.php£¬car/buy.php

ÉÏÊoµÄÒ»Ð(C)¹aeÔoÊÇΪÁËÄÜÔÚ³ÌÐoÖиuºÃµÄ½øÐл¥ÏaµÄµ÷Ó᣽ÓÏÂÀ´¾Í¿ªÊ¼ÕaeÕýµÄPHP MVC±a³ÌÁË¡£

3.3 Öض¨Ïo

½«ËuÓеÄÊý¾ÝÇeÇo¶¼Öض¨Ïo index.php Îļþ£¬ÔÚ todo Ŀ¼ÏÂн¨Ò»¸o .htaccess Îļþ£¬ÎļþÄÚÈÝΪ£º


    <IfModule mod_rewrite.c>
      RewriteEngine On

      # È*±£ÇeÇoÂ*¾¶²»ÊÇÒ»¸oÎļþÃu»oĿ¼
      RewriteCond %{REQUEST_FILENAME} !-f
      RewriteCond %{REQUEST_FILENAME} !-d

      # Öض¨ÏoËuÓÐÇeÇoµ½ index.php?url=PATHNAME
      RewriteRule ^(.*)$ index.php?url=$1 [PT,L]
    </IfModule>

ÕaÑu×oµÄÖ÷ÒªÔ­ÒoÓУº
1.³ÌÐoÓÐÒ»¸oµ¥Ò»µÄÈe¿Ú£»
2.³ý¾²Ì¬³ÌÐo£¬ÆaËuËuÓгÌÐo¶¼Öض¨Ïoµ½ index.php ÉÏ£»
3.¿ÉÒÔÓÃÀ´Éu³ÉÀuÓÚSEOµÄURL£¬ÏeÒª¸uºÃµÄÅaÖÃURL£¬ºoÆÚ¿ÉÄÜ»aÐeÒªURLÂ*ÓÉ£¬ÕaÀiÏȲ»×o½eÉÜÁË¡£

3.4 Èe¿ÚÎļþ

×oÍeÉÏÃaeµÄ²Ù×÷£¬¾ÍÓ¦¸ÃÖªµÀÎÒÃÇÐeÒª×oʲôÁË£¬Ã»´i£¡ÔÚ public Ŀ¼ÏÂÌi¼Ó index.php Îļþ£¬ÎļþÄÚÈÝΪ£º


     <?php

    // Ó¦ÓÃĿ¼Ϊµ±Ç°Ä¿Â¼
    define('APP_PATH', __DIR__.'/');

    // ¿ªÆoµ÷ÊÔģʽ
    define('APP_DEBUG', true);

    // ÍøÕ¾¸uURL
    define('APP_URL', 'http://localhost/fastphp');

    // ¼ÓÔØ¿o¼Ü
    require './fastphp/FastPHP.php';

×¢Òa£¬ÉÏÃaeµÄPHP´uÂeÖУ¬²¢Ã»ÓÐÌi¼ÓPHP½aÊøuºÅ¡±?>¡±£¬Õaô×oµÄÖ÷ÒªÔ­ÒoÊÇ£¬¶ÔÓÚÖ»ÓÐ PHP ´uÂeµÄÎļþ£¬½aÊø±eÖ¾(¡°?>¡±)×iºÃ²»´aeÔÚ£¬PHP×ÔÉi²¢²»ÐeÒª½aÊøuºÅ£¬²»Ìi¼Ó½aÊøuºÅ¿ÉÒԺܴo³Ì¶ÈÉÏÀÖ¹Ä(C)β±»Ìi¼Ó¶iÍaµÄ×¢ÈeÄÚÈÝ£¬ÈóÌÐo¸u¼Ó°²È«¡£

3.5 ÅaÖÃÎļþºÍÖ÷ÇeÇo

ÔÚ index.php ÖУ¬ÎÒÃÇ¶Ô fastphp Îļþ¼ÐÏ嵀 FastPHP.php *¢ÆðÁËÇeÇo£¬ÄÇô FastPHP.php Õa¸oÆo¶¯ÎļþÖе½µ×»a°uº¬ÄÄÐ(C)ÄÚÈÝÄØ£¿


    <?php

    // ³oʼ»¯³£Á¿
    defined('FRAME_PATH') or define('FRAME_PATH', __DIR__.'/');
    defined('APP_PATH') or define('APP_PATH', dirname($_SERVER['SCRIPT_FILENAME']).'/');
    defined('APP_DEBUG') or define('APP_DEBUG', false);
    defined('CONFIG_PATH') or define('CONFIG_PATH', APP_PATH.'config/');
    defined('RUNTIME_PATH') or define('RUNTIME_PATH', APP_PATH.'runtime/');

    // °uº¬ÅaÖÃÎļþ
    require APP_PATH . 'config/config.php';

    //°uº¬ºËÐÄ¿o¼ÜÀa
    require FRAME_PATH . 'Core.php';

    // ʵÀý»¯ºËÐÄÀa
    $fast = new Core;
    $fast->run();

ÒÔÉÏÎļþ¶¼Æaʵ¿ÉÒÔÖ±½ÓÔÚ index.php ÎļþÖаuº¬£¬³£Á¿Ò²¿ÉÒÔÖ±½ÓÔÚ index.php Öж¨Òa£¬ÎÒÃÇÕaô×oµÄÔ­ÒoÊÇΪÁËÔÚºoÆÚ¹ÜÀiºÍÍØÕ¹Öиu¼ÓµÄ½±a£¬ËuÒÔ°ÑÐeÒªÔÚÒ»¿ªÊ¼µÄʱºo¾Í¼ÓÔØÔËÐеijÌÐoͳһŵ½Ò»¸oµ¥¶ÀµÄÎļþÖÐÒýÓá£

ÏÈÀ´¿´¿´configÎļþÏ嵀 config .php Îļþ£¬¸ÃÎļþµÄÖ÷Òª×÷ÓÃÊÇÉeÖÃÒ»Ð(C)³ÌÐoµÄÅaÖÃÏi¼°Êý¾Ý¿aÁ¬½ÓµÈ£¬Ö÷ÒªÄÚÈÝΪ£º


     <?php

    /** ±aÁ¿ÅaÖà **/

    define('DB_NAME', 'todo');
    define('DB_USER', 'root');
    define('DB_PASSWORD', 'root');
    define('DB_HOST', 'localhost');

Ó¦¸Ã˵ config.php Éae¼°µ½µÄÄÚÈݲ¢²»¶a£¬²»¹ýÊÇÒ»Ð(C)»u´¡Êý¾Ý¿aµÄÉeÖã¬ÔÙÀ´¿´¿´ fastphpÏµĹ²Óÿo¼ÜÈe¿ÚÎļþ Core.php Ó¦¸ÃÔoôд¡£


    <?php
    /**
     * FastPHPºËÐÄ¿o¼Ü
     */
    class Core
    {
      // ÔËÐгÌÐo
      function run()
      {
        spl_autoload_register(array($this, 'loadClass'));
        $this->setReporting();
        $this->removeMagicQuotes();
        $this->unregisterGlobals();
        $this->Route();
      }

      // Â*ÓÉ´¦Ài
      function Route()
      {
        $controllerName = 'Index';
        $action = 'index';

        if (!empty($_GET['url'])) {
          $url = $_GET['url'];
          $urlArray = explode('/', $url);

          // »ñÈ¡¿ØÖÆÆ÷Ãu
          $controllerName = ucfirst($urlArray[0]);

          // »ñÈ¡¶¯×÷Ãu
          array_shift($urlArray);
          $action = empty($urlArray[0]) ? 'index' : $urlArray[0];

          //»ñÈ¡URL²ÎÊý
          array_shift($urlArray);
          $queryString = empty($urlArray) ? array() : $urlArray;
        }

        // Êý¾ÝΪ¿ÕµÄ´¦Ài
        $queryString = empty($queryString) ? array() : $queryString;

        // ʵÀý»¯¿ØÖÆÆ÷
        $controller = $controllerName . 'Controller';
        $dispatch = new $controller($controllerName, $action);

        // Èç¹u¿ØÖÆÆ÷´aeºÍ¶¯×÷´aeÔÚ£¬Õaµ÷Óò¢´«ÈeURL²ÎÊý
        if ((int)method_exists($controller, $action)) {
          call_user_func_array(array($dispatch, $action), $queryString);
        } else {
          exit($controller . "¿ØÖÆÆ÷²»´aeÔÚ");
        }
      }

      // ¼i²a¿ª*¢»*¾³
      function setReporting()
      {
        if (APP_DEBUG === true) {
          error_reporting(E_ALL);
          ini_set('display_errors','On');
        } else {
          error_reporting(E_ALL);
          ini_set('display_errors','Off');
          ini_set('log_errors', 'On');
          ini_set('error_log', RUNTIME_PATH. 'logs/error.log');
        }
      }

      // ɾ³ýÃo¸Ð×Ö*u
      function stripSlashesDeep($value)
      {
        $value = is_array($value) ? array_map('stripSlashesDeep', $value) : stripslashes($value);
        return $value;
      }

      // ¼i²aÃo¸Ð×Ö*u²¢É¾³ý
      function removeMagicQuotes()
      {
        if ( get_magic_quotes_gpc()) {
          $_GET = stripSlashesDeep($_GET );
          $_POST = stripSlashesDeep($_POST );
          $_COOKIE = stripSlashesDeep($_COOKIE);
          $_SESSION = stripSlashesDeep($_SESSION);
        }
      }

      // ¼i²a×Ô¶¨ÒaÈ«¾Ö±aÁ¿£¨register globals£(C)²¢ÒƳý
      function unregisterGlobals()
      {
        if (ini_get('register_globals')) {
          $array = array('_SESSION', '_POST', '_GET', '_COOKIE', '_REQUEST', '_SERVER', '_ENV', '_FILES');
          foreach ($array as $value) {
            foreach ($GLOBALS[$value] as $key => $var) {
              if ($var === $GLOBALS[$key]) {
                unset($GLOBALS[$key]);
              }
            }
          }
        }
      }

      // ×Ô¶¯¼ÓÔØ¿ØÖÆÆ÷ºÍÄ£ÐÍÀa 
      static function loadClass($class)
      {
        $frameworks = FRAME_PATH . $class . '.class.php';
        $controllers = APP_PATH . 'application/controllers/' . $class . '.class.php';
        $models = APP_PATH . 'application/models/' . $class . '.class.php';

        if (file_exists($frameworks)) {
          // ¼ÓÔØ¿o¼ÜºËÐÄÀa
          include $frameworks;
        } elseif (file_exists($controllers)) {
          // ¼ÓÔØÓ¦ÓÿØÖÆÆ÷Àa
          include $controllers;
        } elseif (file_exists($models)) {
          //¼ÓÔØÓ¦ÓÃÄ£ÐÍÀa
          include $models;
        } else {
          /* ´iÎo´uÂe */
        }
      }
    }

ÏÂÃaeÖصa½²½aÖ÷ÇeÇo½¨ callHook()£¬Ê×ÏÈÎÒÃÇÏe¿´¿´ÎÒÃÇµÄ URL »aÕaÑu£º
yoursite.com/controllerName/actionName/queryString

callHook()µÄ×÷ÓþÍÊÇ£¬´ÓÈ«¾Ö±aÁ¿ G ET[ ¡a url ¡a ]±aÁ¿ÖлñÈ¡URL£¬²¢½«ÆaÖ¸i³ÉÈý²¿Ö£º GET[¡aurl¡a]±aÁ¿ÖлñÈ¡URL£¬²¢½«ÆaÖ¸i³ÉÈý²¿Ö£ºcontroller¡¢actionºÍ actionºÍqueryString¡£

ÀýÈ磬URLÁ´½ÓΪ£ºtodo.com/item/view/1/first-item£¬ÄÇô
•$controller ¾ÍÊÇ£ºitem
•$action ¾ÍÊÇ£ºview
•²eѯ×Ö*u´®Query String¾ÍÊÇ£ºarray(1, first-item)

Ö¸iÍe³Éºo£¬»aʵÀý»¯Ò»¸oеĿØÖÆÆ÷£º$controller.'Controller'£¨ÆaÖС°.¡±ÊÇÁ¬×Öu£(C)£¬²¢µ÷ÓÃÆa½¨ $action¡£

3.6 ¿ØÖÆÆ÷/Controller»uÀa

½ÓÏÂÀ´µÄ²Ù×÷¾ÍÊÇÔÚ fastphp Öн¨Á¢³ÌÐoËuÐeµÄ»uÀa£¬°uÀ¨¿ØÖÆÆ÷¡¢Ä£ÐͺÍÊÓͼµÄ»uÀa¡£

н¨¿ØÖÆÆ÷»uÀaΪ Controller.class.php£¬¿ØÖÆÆ÷µÄÖ÷Òª¹¦ÄܾÍÊÇ×ܵ÷¶È£¬¾ßÌa¾ßÌaÄÚÈÝÈçÏ£º


    <?php 
    /**
     * ¿ØÖÆÆ÷»uÀa
     */
    class Controller
    {
      protected $_controller;
      protected $_action;
      protected $_view;

      // ¹¹Ôiº¯Êý£¬³oʼ»¯ÊoÐÔ£¬²¢ÊµÀý»¯¶ÔӦģÐÍ
      function __construct($controller, $action)
      {
        $this->_controller = $controller;
        $this->_action = $action;
        $this->_view = new View($controller, $action);
      }

      // *ÖÅa±aÁ¿
      function assign($name, $value)
      {
        $this->_view->assign($name, $value);
      }

      // aÖȾÊÓͼ
      function __destruct()
      {
        $this->_view->render();
      }
    }

Controller ÀaʵÏÖËuÓпØÖÆÆ÷¡¢Ä£ÐͺÍÊÓͼ£¨ViewÀa£(C)µÄͨÐÅ¡£ÔÚÖ´ÐÐÎo¹¹º¯Êýʱ£¬ÎÒÃÇ¿ÉÒÔµ÷Óà render() À´ÏÔʾÊÓͼ£¨view£(C)Îļþ¡£

3.7 Ä£ÐÍModel»uÀa

н¨Ä£ÐÍ»uÀaΪ Model.class.php£¬Ä£ÐÍ»uÀa Model.class.php ´uÂeÈçÏ£º


     <?php

    class Model extends Sql
    {
      protected $_model;
      protected $_table;

      function __construct()
      {
        // Á¬½ÓÊý¾Ý¿a
        $this->connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);

        // »ñÈ¡Ä£ÐÍÃu³Æ
        $this->_model = get_class($this);
        $this->_model = rtrim($this->_model, 'Model');

        // Êý¾Ý¿a±iÃuÓeÀaÃuÒ»ÖÂ
        $this->_table = strtolower($this->_model);
      }

      function __destruct()
      {
      }
    }

¿¼Âǵ½Ä£ÐÍÐeÒª¶ÔÊý¾Ý¿a½øÐд¦Ài£¬ËuÒÔµ¥¶À½¨Á¢Ò»¸oÊý¾Ý¿a»uÀa Sql.class.php£¬Ä£ÐÍ»uÀa¼Ì³Ð Sql.class.php£¬´uÂeÈçÏ£º


     <?php

    class Sql
    {
      protected $_dbHandle;
      protected $_result;

      // Á¬½ÓÊý¾Ý¿a
      public function connect($host, $user, $pass, $dbname)
      {
        try {
          $dsn = sprintf("mysql:host=%s;dbname=%s;charset=utf8", $host, $dbname);
          $this->_dbHandle = new PDO($dsn, $user, $pass, array(PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC));
        } catch (PDOException $e) {
          exit('´iÎo: ' . $e->getMessage());
        }
      }

      // ²eѯËuÓÐ
      public function selectAll()
      {
        $sql = sprintf("select * from `%s`", $this->_table);
        $sth = $this->_dbHandle->prepare($sql);
        $sth->execute();

        return $sth->fetchAll();
      }

      // ¸u¾ÝÌo¼þ (id) ²eѯ
      public function select($id)
      {
        $sql = sprintf("select * from `%s` where `id` = '%s'", $this->_table, $id);
        $sth = $this->_dbHandle->prepare($sql);
        $sth->execute();

        return $sth->fetch();
      }

      // ¸u¾ÝÌo¼þ (id) ɾ³ý
      public function delete($id)
      {
        $sql = sprintf("delete from `%s` where `id` = '%s'", $this->_table, $id);
        $sth = $this->_dbHandle->prepare($sql);
        $sth->execute();

        return $sth->rowCount();
      }

      // ×Ô¶¨ÒaSQL²eѯ£¬*µ»ØÓ°ÏiµÄÐÐÊý
      public function query($sql)
      {
        $sth = $this->_dbHandle->prepare($sql);
        $sth->execute();

        return $sth->rowCount();
      }

      // ÐÂÔoÊý¾Ý
      public function add($data)
      {
        $sql = sprintf("insert into `%s` %s", $this->_table, $this->formatInsert($data));

        return $this->query($sql);
      }

      // ÐÞ¸ÄÊý¾Ý
      public function update($id, $data)
      {
        $sql = sprintf("update `%s` set %s where `id` = '%s'", $this->_table, $this->formatUpdate($data), $id);

        return $this->query($sql);
      }

      // ½«Êý×eת»»³É²aÈe¸ñʽµÄsqlÓi¾a
      private function formatInsert($data)
      {
        $fields = array();
        $values = array();
        foreach ($data as $key => $value) {
          $fields[] = sprintf("`%s`", $key);
          $values[] = sprintf("'%s'", $value);
        }

        $field = implode(',', $fields);
        $value = implode(',', $values);

        return sprintf("(%s) values (%s)", $field, $value);
      }

      // ½«Êý×eת»»³É¸uиñʽµÄsqlÓi¾a
      private function formatUpdate($data)
      {
        $fields = array();
        foreach ($data as $key => $value) {
          $fields[] = sprintf("`%s` = '%s'", $key, $value);
        }

        return implode(',', $fields);
      }
    }

Ó¦¸Ã˵£¬Sql.class.php ÊÇ¿o¼ÜµÄºËÐIJ¿*Ö¡£ÎªÊ²Ã´£¿ÒoΪͨ¹ýËu£¬ÎÒÃÇ´´½¨ÁËÒ»¸o SQL ³eÏo²a£¬¿ÉÒÔ´o´o¼oÉÙÁËÊý¾Ý¿aµÄ±a³Ì¹¤×÷¡£ËaÈ» PDO ½Ó¿Ú±¾À´ÒѾ­ºÜ¼o½a£¬µ«ÊdzeÏoÖ®ºo¿o¼ÜµÄ¿ÉÁe»iÐÔ¸u¸ß¡£

3.8 ÊÓͼViewÀa

ÊÓͼÀa View.class.php ÄÚÈÝÈçÏ£º


     <?php
    /**
     * ÊÓͼ»uÀa
     */
    class View
    {
      protected $variables = array();
      protected $_controller;
      protected $_action;

      function __construct($controller, $action)
      {
        $this->_controller = $controller;
        $this->_action = $action;
      }

      /** *ÖÅa±aÁ¿ **/
      function assign($name, $value)
      {
        $this->variables[$name] = $value;
      }

      /** aÖȾÏÔʾ **/
      function render()
      {
        extract($this->variables);
        $defaultHeader = APP_PATH . 'application/views/header.php';
        $defaultFooter = APP_PATH . 'application/views/footer.php';
        $controllerHeader = APP_PATH . 'application/views/' . $this->_controller . '/header.php';
        $controllerFooter = APP_PATH . 'application/views/' . $this->_controller . '/footer.php';

        // Ò³Í*Îļþ
        if (file_exists($controllerHeader)) {
          include ($controllerHeader);
        } else {
          include ($defaultHeader);
        }

        // Ò³ÄÚÈÝÎļþ
        include (APP_PATH . 'application/views/' . $this->_controller . '/' . $this->_action . '.php');

        // Ò³½ÅÎļþ
        if (file_exists($controllerFooter)) {
          include ($controllerFooter);
        } else {
          include ($defaultFooter);
        }
      }
    }

ÕaÑuÎÒÃǵĺËÐĵÄPHP MVC¿o¼Ü¾Í±aдÍe³ÉÁË£¬ÏÂÃaeÎÒÃÇ¿ªÊ¼±aдӦÓÃÀ´²aÊÔ¿o¼Ü¹¦ÄÜ¡£

4 Ó¦ÓÃ

4.1 Êý¾Ý¿a²¿Êð

ÔÚ SQL ÖÐн¨Ò»¸o todo Êý¾Ý¿a£¬Ê¹ÓÃÏÂÃaeµÄÓi¾aÔo¼Ó item Êý¾Ý±i²¢²aÈe2Ìo¼Ç¼£º


    CREATE DATABASE `todo` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
    USE `todo`;

    CREATE TABLE `item` (
      `id` int(11) NOT NULL auto_increment,
      `item_name` varchar(255) NOT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

    INSERT INTO `item` VALUES(1, 'Hello World.');
    INSERT INTO `item` VALUES(2, 'Lets go!'); 

4.2 ²¿ÊðÄ£ÐÍ

È»ºo£¬ÎÒÃÇ»¹ÐeÒªÔÚ models Ŀ¼Öд´½¨Ò»¸o ItemModel.php Ä£ÐÍ£¬ÄÚÈÝÈçÏ£º


     <?php

    class ItemModel extends Model
    {
      /* ÒµÎñÂß¼­²aʵÏÖ */
    }

Ä£ÐÍÄÚÈÝΪ¿Õ¡£ÒoΪ Item Ä£Ðͼ̳ÐÁË Model£¬ËuÒÔËuÓµÓÐ Model µÄËuÓй¦ÄÜ¡£

4.3 ²¿Êð¿ØÖÆÆ÷

ÔÚ controllers Ŀ¼Ï´´½¨Ò»¸o ItemController.php ¿ØÖÆÆ÷£¬ÄÚÈÝÈçÏ£º


     <?php

    class ItemController extends Controller
    {
      // Ê×Ò³*½*¨£¬²aÊÔ¿o¼Ü×Ô¶¨ÒaDB²eѯ
      public function index()
      {
        $items = (new ItemModel)->selectAll();

        $this->assign('title', 'È«²¿ÌoÄ¿');
        $this->assign('items', $items);
      }

      // Ìi¼Ó¼Ç¼£¬²aÊÔ¿o¼ÜDB¼Ç¼´´½¨£¨Create£(C)
      public function add()
      {
        $data['item_name'] = $_POST['value'];
        $count = (new ItemModel)->add($data);

        $this->assign('title', 'Ìi¼Ó³É¹¦');
        $this->assign('count', $count);
      }

      // ²e¿´¼Ç¼£¬²aÊÔ¿o¼ÜDB¼Ç¼¶ÁÈ¡£¨Read£(C)
      public function view($id = null)
      {
        $item = (new ItemModel)->select($id);

        $this->assign('title', 'ÕýÔÚ²e¿´' . $item['item_name']);
        $this->assign('item', $item);
      }

      // ¸uмǼ£¬²aÊÔ¿o¼ÜDB¼Ç¼¸uУ¨Update£(C)
      public function update()
      {
        $data = array('id' => $_POST['id'], 'item_name' => $_POST['value']);
        $count = (new ItemModel)->update($data['id'], $data);

        $this->assign('title', 'Ð޸ijɹ¦');
        $this->assign('count', $count);
      }

      // ɾ³ý¼Ç¼£¬²aÊÔ¿o¼ÜDB¼Ç¼ɾ³ý£¨Delete£(C)
      public function delete($id = null)
      {
        $count = (new ItemModel)->delete($id);

        $this->assign('title', 'ɾ³ý³É¹¦');
        $this->assign('count', $count);
      }
    }

4.4 ²¿ÊðÊÓͼ

ÔÚ views Ŀ¼ÏÂн¨ header.php ºÍ footer.php Á½¸oÒ³Í*Ò³½ÅÄ£°a£¬ÄÚÈÝÈçÏ¡£

header.php£¬ÄÚÈÝ£º


     <html>
    <head>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
      <title><?php echo $title ?></title>
      <style>
        .item {
          width:400px;
        }

        input {
          color:#222222;
          font-family:georgia,times;
          font-size:24px;
          font-weight:normal;
          line-height:1.2em;
          color:black;
        }

        a {
          color:blue;
          font-family:georgia,times;
          font-size:20px;
          font-weight:normal;
          line-height:1.2em;
          text-decoration:none;
         }

        a:hover {
          text-decoration:underline;
        }

        h1 {
          color:#000000;
          font-size:41px;
          letter-spacing:-2px;
          line-height:1em;
          font-family:helvetica,arial,sans-serif;
          border-bottom:1px dotted #cccccc;
        }

        h2 {
          color:#000000;
          font-size:34px;
          letter-spacing:-2px;
          line-height:1em;
          font-family:helvetica,arial,sans-serif;
        }
      </style>
    </head>
    <body>
      <h1><?php echo $title ?></h1>

    footer.php£¬ÄÚÈÝ£º
     </body>
    </html>

È»ºo£¬ÔÚ views/item ´´½¨ÒÔϼ¸¸oÊÓͼÎļþ¡£

index.php£¬a¯ÀÀÊý¾Ý¿aÄÚ item ±iµÄËuÓмǼ£¬ÄÚÈÝ£º


     <form action="<?php echo APP_URL ?>/item/add" method="post">
      <input type="text" value="µa»÷Ìi¼Ó" onclick="this.value=''" name="value">
      <input type="submit" value="Ìi¼Ó">
    </form>
    <br/><br/>

    <?php $number = 0?>

    <?php foreach ($items as $item): ?>
      <a class="big" href="<?php echo APP_URL ?>/item/view/<?php echo $item['id'] ?>" title="µa»÷ÐÞ¸Ä">
        <span class="item">
          <?php echo ++$number ?>
          <?php echo $item['item_name'] ?>
        </span>
      </a>
      ----
      <a class="big" href="<?php echo APP_URL ?>/item/delete/<?php echo $item['id']?>">ɾ³ý</a>
    <br/>
    <?php endforeach ?>

add.php£¬Ìi¼Ó¼Ç¼£¬ÄÚÈÝ£º
³É¹¦Ìi¼Ó<?php echo $count ?>Ìo¼Ç¼£¬µa»÷*µ»Ø

view.php£¬²e¿´µ¥Ìo¼Ç¼£¬ÄÚÈÝ£º


     <form action="<?php echo APP_URL ?>/item/update" method="post">
      <input type="text" name="value" value="<?php echo $item['item_name'] ?>">
      <input type="hidden" name="id" value="<?php echo $item['id'] ?>">
      <input type="submit" value="ÐÞ¸Ä">
    </form>

    <a class="big" href="<?php echo APP_URL ?>/item/index">*µ»Ø</a>

update.php£¬¸u¸Ä¼Ç¼£¬ÄÚÈÝ£º
³É¹¦ÐÞ¸Ä<?php echo $count ?>Ïi£¬µa»÷*µ»Ø

delete.php£¬É¾³ý¼Ç¼£¬ÄÚÈÝ£º
³É¹¦É¾³ý<?php echo $count ?>Ïi£¬µa»÷*µ»Ø

4.5 Ó¦ÓòaÊÔ

ÕaÑu£¬ÔÚa¯ÀÀÆ÷ÖÐ*ÃÎÊ todo ³ÌÐo£ºhttp://localhost/todo/item/index/£¬¾Í¿ÉÒÔ¿´µ½Ð§¹uÁË¡£

ÒÔÉÏ´uÂeÒѾ­È«²¿¢²¼µ½ github ÉÏ£¬¹Ø¼u²¿Ö¼Óº½ÁË×¢ÊÍ£¬²Ö¿aµØÖ*£ºhttps://github.com/yeszao/fastphp£¬»¶Ó­¿Ë¡¡¢Ìa½»¡£

ÒªÉe¼Æ¸uºÃµÄMVC£¬»oʹÓõøu¼Ó¹ae¶£¬Çe¿´¡¶[MVC¼Ü¹¹µÄÖ°Ôð»®ÖÔ­Ôo¡*](http://www.awaimai.com/873.html) ¡£

ÒÔÉϾÍÊDZ¾ÎĵÄÈ«²¿ÄÚÈÝ£¬Ï£Íu¶Ô´o¼ÒµÄѧϰÓÐËu°iÖu£¬Ò²Ï£Íu´o¼Ò¶a¶aÖ§³Ö½Å±¾Ö®¼Ò¡£

 相关文章:
PHP分页显示制作详细讲解
SSH 登录失败:Host key verification failed
获取IMSI
将二进制数据转为16进制以便显示
获取IMEI
文件下载
贪吃蛇
双位运算符
PHP自定义函数获取搜索引擎来源关键字的方法
Java生成UUID
发送邮件
年的日历图
提取后缀名
在Zeus Web Server中安装PHP语言支持
让你成为最历害的git提交人
Yii2汉字转拼音类的实例代码
再谈PHP中单双引号的区别详解
指定应用ID以获取对应的应用名称
Python 2与Python 3版本和编码的对比
php封装的page分页类完整实例