Composer中的自動載入
Composer是PHP的一個包依賴管理工具,類似Ruby中的RubyGems或者Node中的NPM,它並非官方,但現在已經非常流行。此文並不介紹如何使用Composer,而是關注於它的autoload的內容吧。
舉例來說,假設我們的專案想要使用monolog這個日誌工具,就需要在composer.json裡告訴composer我們需要它:
{
"require": {
"monolog/monolog": "1.*"
}
}
之後執行:
php composer.phar install
好,現在安裝完了,該怎麼使用呢?Composer自動生成了一個autoload檔案,你只需要引用它
require '/path/to/vendor/autoload.php';
然後就可以非常方便的去使用第三方的類庫了,是不是感覺很棒啊!對於我們需要的monolog,就可以這樣用了:
在這個過程中,Composer做了什麼呢?它生成了一個autoloader,再根據各個包自己的autoload配置,從而幫我們進行自動載入的工作。(如果對autoload這部分內容不太瞭解,可以看我之前的一篇文章)接下來讓我們看看Composer是怎麼做的吧。use Monolog\Logger; use Monolog\Handler\StreamHandler; // create a log channel $log = new Logger('name'); $log->pushHandler(new StreamHandler('/path/to/log/log_name.log', Logger::WARNING)); // add records to the log $log->addWarning('Foo'); $log->addError('Bar');
對於第三方包的自動載入,Composer提供了四種方式的支援,分別是 PSR-0和PSR-4的自動載入(我的一篇文章也有介紹過它們),生成class-map,和直接包含files的方式。
PSR-4是composer推薦使用的一種方式,因為它更易使用並能帶來更簡潔的目錄結構。在composer.json裡是這樣進行配置的:
key和value就定義出了namespace以及到相應path的對映。按照PSR-4的規則,當試圖自動載入"Foo\\Bar\\Baz"這個class時,會去尋找"src/Bar/Baz.php"這個檔案,如果它存在則進行載入。注意,"Foo\\"並沒有出現在檔案路徑中,這是與PSR-0不同的一點,如果PSR-0有此配置,那麼會去尋找"src/Foo/Bar/Baz.php"這個檔案。{ "autoload": { "psr-4": { "Foo\\": "src/", } } }
另外注意PSR-4和PSR-0的配置裡,"Foo\\"結尾的名稱空間分隔符必須加上並且進行轉義,以防出現"Foo"匹配到了"FooBar"這樣的意外發生。
在composer安裝或更新完之後,psr-4的配置換被轉換成namespace為key,dir path為value的Map的形式,並寫入生成的vendor/composer/autoload_psr4.php檔案之中。
PSR-0與PSR-4類似:
{
"autoload": {
"psr-0": {
"Foo\\": "src/",
}
}
}
最終這個配置也以Map的形式寫入生成的vendor/composer/autoload_namespaces.php檔案之中。
Class-map方式,則是通過配置指定的目錄或檔案,然後在Composer安裝或更新時,它會掃描指定目錄下以.php或.inc結尾的檔案中的class,生成class到指定file path的對映,並加入新生成的vendor/composer/autoload_classmap.php檔案中,。
{
"autoload": {
"classmap": ["src/", "lib/", "Something.php"]
}
}
例如src/下有一個BaseController類,那麼在autoload_classmap.php檔案中,就會生成這樣的配置:
'BaseController' => $baseDir . '/src/BaseController.php'
Files方式,就是手動指定供直接載入的檔案。比如說我們有一系列全域性的helper functions,可以放到一個helper檔案裡然後直接進行載入
{
"autoload": {
"files": ["src/MyLibrary/functions.php"]
}
}
它會生成一個array,包含這些配置中指定的files,再寫入新生成的vendor/composer/autoload_files.php檔案中,以供autoloader直接進行載入。
下面來看看composer autoload的程式碼吧
<?php
// autoload_real.php @generated by Composer
class ComposerAutoloaderInit73612b48e6c3d0de8d56e03dece61d11
{
private static $loader;
public static function loadClassLoader($class)
{
if ('Composer\Autoload\ClassLoader' === $class) {
require __DIR__ . '/ClassLoader.php';
}
}
public static function getLoader()
{
if (null !== self::$loader) {
return self::$loader;
}
spl_autoload_register(array('ComposerAutoloaderInit73612b48e6c3d0de8d56e03dece61d11', 'loadClassLoader'), true, true);
self::$loader = $loader = new \Composer\Autoload\ClassLoader();
spl_autoload_unregister(array('ComposerAutoloaderInit73612b48e6c3d0de8d56e03dece61d11', 'loadClassLoader'));
$vendorDir = dirname(__DIR__); //verdor第三方類庫提供者目錄
$baseDir = dirname($vendorDir); //整個應用的目錄
$includePaths = require __DIR__ . '/include_paths.php';
array_push($includePaths, get_include_path());
set_include_path(join(PATH_SEPARATOR, $includePaths));
$map = require __DIR__ . '/autoload_namespaces.php';
foreach ($map as $namespace => $path) {
$loader->set($namespace, $path);
}
$map = require __DIR__ . '/autoload_psr4.php';
foreach ($map as $namespace => $path) {
$loader->setPsr4($namespace, $path);
}
$classMap = require __DIR__ . '/autoload_classmap.php';
if ($classMap) {
$loader->addClassMap($classMap);
}
$loader->register(true);
$includeFiles = require __DIR__ . '/autoload_files.php';
foreach ($includeFiles as $file) {
composerRequire73612b48e6c3d0de8d56e03dece61d11($file);
}
return $loader;
}
}
function composerRequire73612b48e6c3d0de8d56e03dece61d11($file)
{
require $file;
}
首先初始化ClassLoader類,然後依次用上面提到的4種載入方式來註冊/直接載入,ClassLoader的一些核心程式碼如下:
/**
* @param array $classMap Class to filename map
*/
public function addClassMap(array $classMap)
{
if ($this->classMap) {
$this->classMap = array_merge($this->classMap, $classMap);
} else {
$this->classMap = $classMap;
}
}
/**
* Registers a set of PSR-0 directories for a given prefix,
* replacing any others previously set for this prefix.
*
* @param string $prefix The prefix
* @param array|string $paths The PSR-0 base directories
*/
public function set($prefix, $paths)
{
if (!$prefix) {
$this->fallbackDirsPsr0 = (array) $paths;
} else {
$this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths;
}
}
/**
* Registers a set of PSR-4 directories for a given namespace,
* replacing any others previously set for this namespace.
*
* @param string $prefix The prefix/namespace, with trailing '\\'
* @param array|string $paths The PSR-4 base directories
*
* @throws \InvalidArgumentException
*/
public function setPsr4($prefix, $paths)
{
if (!$prefix) {
$this->fallbackDirsPsr4 = (array) $paths;
} else {
$length = strlen($prefix);
if ('\\' !== $prefix[$length - 1]) {
throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
}
$this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
$this->prefixDirsPsr4[$prefix] = (array) $paths;
}
}
/**
* Registers this instance as an autoloader.
*
* @param bool $prepend Whether to prepend the autoloader or not
*/
public function register($prepend = false)
{
spl_autoload_register(array($this, 'loadClass'), true, $prepend);
}
/**
* Loads the given class or interface.
*
* @param string $class The name of the class
* @return bool|null True if loaded, null otherwise
*/
public function loadClass($class)
{
if ($file = $this->findFile($class)) {
includeFile($file);
return true;
}
}
/**
* Finds the path to the file where the class is defined.
*
* @param string $class The name of the class
*
* @return string|false The path if found, false otherwise
*/
public function findFile($class)
{
//這是PHP5.3.0 - 5.3.2的一個bug 詳見https://bugs.php.net/50731
if ('\\' == $class[0]) {
$class = substr($class, 1);
}
// class map 方式的查詢
if (isset($this->classMap[$class])) {
return $this->classMap[$class];
}
//psr-0/4方式的查詢
$file = $this->findFileWithExtension($class, '.php');
// Search for Hack files if we are running on HHVM
if ($file === null && defined('HHVM_VERSION')) {
$file = $this->findFileWithExtension($class, '.hh');
}
if ($file === null) {
// Remember that this class does not exist.
return $this->classMap[$class] = false;
}
return $file;
}
private function findFileWithExtension($class, $ext)
{
// PSR-4 lookup
$logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext;
$first = $class[0];
if (isset($this->prefixLengthsPsr4[$first])) {
foreach ($this->prefixLengthsPsr4[$first] as $prefix => $length) {
if (0 === strpos($class, $prefix)) {
foreach ($this->prefixDirsPsr4[$prefix] as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $length))) {
return $file;
}
}
}
}
}
// PSR-4 fallback dirs
foreach ($this->fallbackDirsPsr4 as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) {
return $file;
}
}
// PSR-0 lookup
if (false !== $pos = strrpos($class, '\\')) {
// namespaced class name
$logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1)
. strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR);
} else {
// PEAR-like class name
$logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext;
}
if (isset($this->prefixesPsr0[$first])) {
foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) {
if (0 === strpos($class, $prefix)) {
foreach ($dirs as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
return $file;
}
}
}
}
}
// PSR-0 fallback dirs
foreach ($this->fallbackDirsPsr0 as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
return $file;
}
}
// PSR-0 include paths.
if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) {
return $file;
}
}
/**
* Scope isolated include.
*
* Prevents access to $this/self from included files.
*/
function includeFile($file)
{
include $file;
}
完。
相關推薦
TP3.1版本下利用composer的自動載入解耦MVC初始化web專案
一. composer自動載入函式庫 很多人說TP框架很low,明明是面向過程的思想非要搭建一個MVC架構。但是不可否認的是,在天朝的phper中,TP作為phpweb開發的先驅者留下了大量歷史問題。。當然,它的簡單易用以及文件的極度完善和php這門類
在Intellij IDEA 中自動載入Maven管理的依賴包的原始碼
如果你的專案不是用 Maven 管理的,可以在專案依賴的Libraries下手工新增依賴包對應的原始碼jar檔案路徑, 方法可以參考此文: https://yq.aliyun.com/articles/72560 但如果你是用 Maven 來管理專案,就不用怎麼麻煩了,只需要在 Intellij IDE
Vim中自動載入cscope.out
Vimer初成長,Vim + ctags + cscope 這個組合基本是每個Vimer的必備吧。雖然ctags已經足夠強大,但是cscope可以做的更多。下面來分享下自己的vimrc指令碼關於cscope的一部分,該指令碼可以實現在專案的任一子目錄下,自動的向上查詢cs
SqlMapConfig.xml --- 在spring配置檔案中自動載入的mybatis檔案
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/d
composer autoload 自動載入效能優化指南
composer 提供的 autoload 機制使得我們組織程式碼和引入新類庫非常方便,但是也使專案的效能下降了不少 。 com
Composer中的自動載入
Composer是PHP的一個包依賴管理工具,類似Ruby中的RubyGems或者Node中的NPM,它並非官方,但現在已經非常流行。此文並不介紹如何使用Composer,而是關注於它的autoload的內容吧。 舉例來說,假設我們的專案想要使用monolog這個日誌工具,
Ecplise中tomcat上執行HTML檔案自動載入
首先說什麼熱部署 今天在做一個SpringBoot的專案時候,發現一個很煩的問題,我修改了HTML然後ecplise上面在server上面執行,但是讓人傷心的是修改的HTML檔案都都需要重啟tomcat 真的太讓人難受了,不可能這樣一直重新啟動啊 修改了半天沒有看出來怎麼解決這樣的
Redhat Linux AS4中行動硬碟自動載入後中文內容為亂碼?
2006-07-29 這個挺傷腦筋, 因為大容量的東西通過網路傳輸比較慢,而在Linux下卻不知裡面是什麼。 先確定locale: ># locale LANG=zh_CN.UTF-8 LC_CTYPE="zh_CN.
Composer自動載入機制原始碼剖析
1、autoload.php 要使用Composer的自動載入,首先需要引入該檔案 <?php // autoload.php @generated by Composer // 引入au
laravel框架關鍵技術解析03-2 composer自動載入
在laravel框架中,通過sql_autoload_register()實現類自動載入函式的註冊。sql_autoload_register自動載入的函式佇列中包含了兩個類的自動載入函式。 一個是composer生成的基於PSR規範的自動載入函式 另一個是laravel框架核心別名
android快速開發框架--快速實現 頁面 載入中 載入失敗 無資料等狀態以及下拉重新整理和自動載入
RapidDevelop-Android快速開發框架 框架持續更新中 這個框架是從平時專案裡用的比較多的框架裡整合而來 對本專案感興趣的可以一起研究喜歡的朋友歡迎star 同時也歡迎大家的寶貴意見issues 如果大家對MVP模式的開發 網路爬蟲以及快取策略
PHP名稱空間自動載入之composer實現方式
必備條件:你已經安裝了composer; 專案構建完成之後的檔案結構: S1: 在專案根目錄建立composer.json檔案,寫入程式碼 { "type": "project", "autoload": { "psr-4": {
ubuntu上使用PHP依賴管理工具Composer(二)——自動載入
結合phpstorm使用Composer命令列 初始化Composer 在phpstorm中建立新的專案test tools->run command(Ctrl+Shift+X)開啟命令
在Linux中如何自動載入驅動模組
在完成驅動除錯後,一直使用insmod 動態的載入驅動模組(ko檔案).會非常麻煩。找到以下辦法: 步驟:1 、開啟下面檔案 sudo vim /etc/moudles 新增
[學習筆記]php中的過載與自動載入
過載技術 通常含義: 在一個類(物件)中有多個名字相同但形參不同的方法的現象。 過載在php中的含義: 當對一個物件或類使用其未定義的屬性或方法的時候,其中的一些“處理機制” 屬性過載: 取值:
php中的自動載入方法的使用
在做專案時我們在使用類檔案之前需要去使用include或require來引入類檔案,如果像圖中這樣 不引入類檔案,而去直接例項化類,會出現檔案未找到的錯誤,如果我們要呼叫的類檔案有多個的話,我們可以使用__autoload()自動呼叫方法引入類檔案如圖: 圖中的這種方法只
PHP中的use、名稱空間、引入類檔案、自動載入類的理解
<div class="postBody"> <div id="cnblogs_post_body" class="cnblogs-markdown"><p>use只是使用了名稱空間,<br>
Eclipse 開發WEB專案 webcontent下lib中的jar包不自動載入的問題
在專案的應用目錄下找到.settings\org.eclipse.wst.common.component檔案, 在剛新建一個專案時,此檔案下面的內容如下:<?xml version="1.0"encoding="UTF-8"?> <project-modules id="module
jsp中自定義標籤自動載入下拉框內容
第一步:在web專案下的web-inf的tlds目錄下,新建一個配置檔案,名字為relation.tld,內容如下: 自定義標籤的字首為relation(由short-name標籤決定),屬性有saveField(要儲存到資料庫的欄位名),value(要被選中的資料值)
ExtJS中store自動載入資料的時候,在firebug下http status為Aborted時的處理方法
本來是一個穩定的功能模組,一直沒有問題,今天在測試資料的時候老是發現載入資料載入失敗,從後臺伺服器的日誌來看,資料已經處理完成,所以和後臺伺服器沒有關係。通過firebug除錯發現,這個ajax請求的status為Aborted,不知道什麼問題導致Aborted這個非標準的