從零開始打造本身的PHP框架——第1章

目標

本篇,咱們來實現類庫自動加載,以及路由解析。php

原文地址:http://www.voidking.com/2017/...linux

類庫自動加載

常規加載

常規加載通常使用include或者require,它們最根本的區別在於錯誤處理的方式不同。 git

include包括並運行指定文件。include一個文件存在錯誤的話,那麼程序不會中斷,而是繼續執行,並顯示一個警告錯誤。github

include_once的做用和include幾乎相同,惟一的差異在於導入以前會檢查要導入的文件是否已經被導入過了,若是有的話就不會再次重複導入。windows

require會將目標文件的內容讀入,而且把自己替換成這些讀入的內容。require一個文件存在錯誤的話,那麼程序就會中斷執行了,並顯示致命錯誤。框架

require_once的做用和require幾乎相同,惟一的差異在於導入以前會檢查要導入的文件是否已經被導入過了,若是有的話就不會再次重複導入。函數

在使用一個文件(類庫)的函數以前,咱們須要先使用include或者require,把該文件引入進當前文件,而後才能使用文件中的函數。ui

例如咱們要新建一個route對象。
一、core目錄中,新建route.php:this

<?php
/**
 * 路由控制
 */
namespace core;
class route{
    public function __construct(){
        echo 'route is ready!';
    }
}

二、根目錄下index.php中,添加:spa

$route = new \core\route();

會報錯Fatal error: Class 'coreroute' not found in...

須要改爲:

include '\core\route.php';
$route = new \core\route();

或者:

require '\core\route.php';
$route = new \core\route();

自動加載

bool spl_autoload_register ([ callable $autoload_function [, bool $throw = true [, bool $prepend = false ]]] )

將函數註冊到SPL __autoload函數隊列中。若是該隊列中的函數還沒有激活,則激活它們。成功時返回 TRUE,失敗時返回 FALSE。

spl_autoload_register的通常用法:

spl_autoload_register(function ($class_name) {
    require_once $class_name . '.php';
});

$route = new \core\route();

在新建route對象時,class_name也就是\core\route會傳入到spl_autoload_register函數中,該函數的參數是一個回調函數。回調函數拿到class_name,而後進行文件的引入。

也就是說,和常規加載相比,使用自動加載,咱們沒必要對每個類庫單獨進行引入。

自動加載進階

上例中,spl_autoload_register的回調函數是一個匿名函數,並且比較簡單。下面,咱們來寫一個更高級的回調函數。新建aotuload.php,內容以下:

<?php
/**
 * 自動加載類庫
 */
namespace core;

class autoload{
    public static function load($class_name){
        if(file_exists($class_name.'.php')){
            require_once $class_name.'.php';
            return true;
        }else{
            echo 'error: unable to load '.$class_name.'.php';
            return false;
        }
    }
}

使用的時候,改爲:

include CORE.'/autoload.php';
spl_autoload_register('\core\autoload::load');
$route = new \core\route();

加載機制簡析

在使用include的時候,會用到php文件系統。在文件系統中訪問一個文件有三種方式:

一、相對文件名形式如route.php。它會被解析爲 include_path/route.php,其中 include_path 表示.;C:/laragon/bin/php/php-5.6.16/PEAR
假設當前目錄是C:/laragon/www/vkphp,則該文件名依次被解析爲:

  • C:/laragon/www/vkphp/route.php
  • C:/laragon/bin/php/php-5.6.16/PEAR/route.php

二、相對路徑名形式如core/route.php,它會被解析爲 include_path/core/route.php
假設當前目錄是C:/laragon/www/vkphp,則該文件名依次被解析爲:

  • C:/laragon/www/vkphp/core/route.php
  • C:/laragon/bin/php/php-5.6.16/PEAR/core/route.php

三、絕對路徑名形式如/core/route.php,在linux系統中,它會被解析爲/core/route.php;在windows系統中,它會被解析爲 include_path/core/route.php,和相對路徑同樣。

絕對路徑名形如C:/laragon/www/vkphp/core/route.php 或者C:\laragon\www\vkphp\core\route.php 或者 C:\\laragon\\www\\vkphp\\core\\route.php ,在windows系統中,會被解析爲C:/laragon/www/vkphp/core/route.php。也就是說,windows中斜線和反斜線和雙反斜線效果相同。

獲取include_path和設置include_path的栗子:

echo get_include_path();
ini_set('include_path', ini_get('include_path').PATH_SEPARATOR.'lib_path/libs');
echo get_include_path();

路由控制

隱藏index.php

一、訪問地址 http://vkphp.dev/index.php ,此時,咱們看到「helloworld」和「route is ready!」。

二、訪問地址 http://vkphp.dev/index.php/in... ,能夠看到一樣的信息。

三、訪問地址 http://vkphp.dev/index/index ,則會報404錯誤。那麼,咱們怎樣隱藏掉index.php呢?答案是添加.htaccess。

在項目根目錄下,添加.htaccess,內容以下:

Options +FollowSymLinks  
IndexIgnore */*  
RewriteEngine on  

# if a directory or a file exists, use it directly  
RewriteCond %{REQUEST_FILENAME} !-f  
RewriteCond %{REQUEST_FILENAME} !-d

# otherwise forward it to index.php  
RewriteRule . index.php

四、訪問地址 http://vkphp.dev/index/index ,能夠看到和一、2中相同的信息。

獲取URL中的控制器和方法

<?php
/**
 * 路由控制
 */
namespace core;

class route{
    public $ctrl;
    public $action;
    public function __construct(){
        //echo 'route is ready!';

        /**
         * 一、隱藏index.php
         * 二、獲取URL中的控制器和方法
         */

        if(isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] != '/'){
            $path = $_SERVER['REQUEST_URI'];
            $patharr = explode('/',trim($path, '/'));
            p($patharr);

            if(isset($patharr[0])){
                if($patharr[0] != 'index.php'){
                    // 省略了index.php
                    $this->ctrl = $patharr[0];

                    if(isset($patharr[1])){
                        $this->action = $patharr[1];
                    } else{
                        $this->action = 'index';
                    }
                }else{
                    // 沒省略index.php
                    if(isset($patharr[1])){
                        $this->ctrl = $patharr[1];
                    }
                    if(isset($patharr[2])){
                        $this->action = $patharr[2];
                    } else{
                        $this->action = 'index';
                    }
                }
            }else{
                $this->ctrl = 'index';
                $this->action = 'index';
            }

        }else{
            $this->ctrl = 'index';
            $this->action = 'index';
        }
    }
}

訪問地址 http://vkphp.dev/index/index 或者 http://vkphp.dev/index.php/in... ,便可看到打印出的patharr信息。

獲取URL中的參數

<?php
/**
 * 路由控制
 */
namespace core;

class route{
    public $ctrl;
    public $action;
    public $params=array();
    public function __construct(){
        //echo 'route is ready!';

        /**
         * 一、隱藏index.php
         * 二、獲取URL中的控制器和方法
         * 三、獲取URL中的參數
         */

        if(isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] != '/'){
            $path = $_SERVER['REQUEST_URI'];
            $patharr = explode('/',trim($path, '/'));
            //p($patharr);

            if(isset($patharr[0])){
                if($patharr[0] != 'index.php'){
                    // 省略了index.php
                    $this->ctrl = $patharr[0];

                    if(isset($patharr[1])){
                        $this->action = $patharr[1];
                    } else{
                        $this->action = 'index';
                    }
                    $count = count($patharr);
                    $i=2;
                    while($i < $count){
                        $this->params[$patharr[$i]] = $patharr[$i+1];
                        $i = $i + 2;
                    }
                }else{
                    // 沒省略index.php
                    if(isset($patharr[1])){
                        $this->ctrl = $patharr[1];
                    }
                    if(isset($patharr[2])){
                        $this->action = $patharr[2];
                    } else{
                        $this->action = 'index';
                    }

                    $count = count($patharr);
                    $i=3;
                    while($i < $count){
                        $this->params[$patharr[$i]] = $patharr[$i+1];
                        $i = $i + 2;
                    }
                }
            }else{
                $this->ctrl = 'index';
                $this->action = 'index';
            }

        }else {
            $this->ctrl = 'index';
            $this->action = 'index';
        }
        p($this->params);
    }
}

訪問地址 http://vkphp.dev/index/index/... 或者 http://vkphp.dev/index.php/in... ,便可看到打印出的params信息。

支持localhost

訪問地址 http://localhost/vkphp/index.... ,沒法正常獲取控制器、方法和參數,修改以下:

<?php
/**
 * 路由控制
 */
namespace core;

class route{
    public $ctrl='index';
    public $action='index';
    public $params=array();
    public function __construct(){
        //echo 'route is ready!';

        /**
         * 一、隱藏index.php
         * 二、獲取URL中的控制器和方法
         * 三、獲取URL中的參數
         */
        if(isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] != '/' ){
            $path = $_SERVER['REQUEST_URI'];
            $patharr = explode('/',trim($path, '/'));
        }else{
            $patharr = array();
        }
        
        if(isset($_SERVER['HTTP_HOST']) && ($_SERVER['HTTP_HOST'] == 'localhost' || $_SERVER['HTTP_HOST'] == '127.0.0.1') ){
            // 去掉項目名稱
            $patharr = array_slice($patharr,1,count($patharr)-1);
        }
        if(isset($patharr[0])){
            if($patharr[0] == 'index.php'){
                // 去掉index.php
                $patharr = array_slice($patharr,1,count($patharr)-1);
            }
            if(isset($patharr[0])){
                $this->ctrl = $patharr[0];
            }
            if(isset($patharr[1])){
                $this->action = $patharr[1];
            } 
            
            $count = count($patharr);
            $i=2;
            while($i < $count){
                if(isset($patharr[$i+1])){
                    $this->params[$patharr[$i]] = $patharr[$i+1];
                }
                $i = $i + 2;
            }
        }
        
        p($this->ctrl);
        p($this->action);
        p($this->params);
    }
}

源碼分享

https://github.com/voidking/v...

書籤

從零開始打造本身的PHP框架

PHP 檔案引入路徑問題

2-php-include-path/)

相關文章
相關標籤/搜索