php composer 實現類的自動加載


我們在開發項目中會經常用到第三方的類庫插件,但是如果每次需要使用的時候都會在代碼的某一處去引入,然后在實例化,這樣做感覺很不方便,那么怎么實現自動加載呢,下面簡單介紹使用composer實現自動加載:

原文地址:小時刻個人博客>http://small.aiweimeng.top/index.php/archives/11.html

 1.首先需要安裝composer
安裝地址(中國鏡像): https://pkg.phpcomposer.com/#how-to-install-composer
根據它的說明一步一步進行安裝
2.安裝好composer以后創建一個工作目錄,eg:work
3.在項目目錄根目錄下建立一個composer.json文件,格式如下:(注意必須為空的json格式文件)

{

}

4.打開命令行控制台cmd,進入工作目錄work,運行composer命令:

composer install

5.運行后會生成composer文件目錄:

- Vendor

 - composer

    - autoload_classmap.php

    - autoload_namespaces.php

    - autoload_psr4.php

    - autoload_real.php

    - autoload_static.php

    ClassLoader.php

    installed.json

    LICENSE

 - autoload.php

- composer.json

6.打開composer.json文件:
共有四種方式:
PSR-0(不推薦使用);
PSR-4;
Class-map;
Files;
下面演示PSR-4實現自動加載:

"autoload": {

   "psr-4": { 
       "src\\": "src/"
    }
}

代碼中```命名空間```(不知道命名空間的話,最好先去搜索查一下)習慣為```目錄名/文件名```
7.新建src目錄,在目錄下創建IndexController.php,php文件內容如下:

//設置命名空間
namespace src;
class IndexController
{
    public function index()
    {
        echo 'indexController';
    }
}

8.使用剛創建的IndexController類:
在work根目錄創建index.php:

//引入vendor下的autoloas.php
require 'vendor/autoload.php';
//實例化對象
$index = new src\\IndexController();
//調用類中的方法
$index->index();

運行后會出現報錯:

class IndexController not fund

打開控制台,進入到work文件目錄,運行composer命令:

composer dump-autoload


在運行work下的index.php,不報錯誤信息說明已經成功實現自動加載了。
9.在work下的index.php文件中我們實例化IndexController類的時,格式為```new src\\IndexController();```;
如果命名空間較長的情況下,看起來不太方便,那我們可以用```use```來引入關鍵字,修改index.php代碼如下:

use src\IndexController;

//引入vendor下的autoloas.php
require 'vendor/autoload.php';
//修改后的實例化
$index = new IndexController();
//調用類中的方法
$index->index();

在運行index.php結果和上面一樣。
**注意:**在配置完composer.json以后一定要運行```composer dump-autoload```不然會出現class not fund;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM