使用Composer自動載入php命名空間

來源:互聯網
上載者:User

這篇文章主要介紹了關於使用Composer自動載入php命名空間 ,有著一定的參考價值,現在分享給大家,有需要的朋友可以參考一下

上一篇介紹了php的命名空間,但是每次都要使用一個spl_autoload_register()或autoload()方法,每個要使用命名空間的地方都要加這個方法太麻煩,有沒有簡單的方法呢?有,可以使用composer自動載入命名空間。
要在php項目中使用包依賴管理工具composer首先得安裝,這個自行搜尋,就不多說了。安裝之後再項目根目錄下建立一個composer.json檔案。
目錄結構如:

composer.json相當於是composer的設定檔.
composer.json

{    "require" : {        "monolog/monolog" : "1.2.*"    },    "autoload" : {        "psr-4" : {            "Test\\" : "vendor/test1/",            "Demo\\" : "vendor/test2/"        }    }}

這個設定檔中有一個autoload段,其中有個psr-4,psr-4是一個基於psr-4(http://www.php-fig.org/psr/psr-4/)規則的類庫自動載入對應關係,只要在其後的對象中,以 “命名空間”: “路徑” 的方式寫入自己的類庫資訊即可。
修改完成後,只要執行一下composer update,對應的目錄結構如。

分別修改 vendor/test1/test.php vendor/test2/test.php
舊 vendor/test1/test.php

<?phpnamespace vendor/test1;class Test{    public function path(){        echo __DIR__."<br>";    }}

新 vendor/test1/test.php

<?phpnamespace Test;class Test{    public function path(){        echo __DIR__."<br>";    }}

vendor/test2/test.php同上,要改成composer.json autoload 對應的命名空間

紅框為命名空間,籃筐為命名空間對應的路徑

index.php加入:require_once DIR.’/vendor/autoload.php’;
index.php

<?php    require_once __DIR__.'/vendor/autoload.php';    $test = new \Test\Test();    $test->path();    $test2 = new \Demo\Test();    $test2->path();

輸出如下:

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.