2017-04-21 32 views
0

基本上,我想使用Composer自動加載器(用於加載第三方庫),但我想繼續使用Zend中的自動加載內置機制1.12Zend 1.12中使用Composer自動加載器(用於加載外部庫)?

我添加了以下一塊代碼:

<?php // File path: index.php 

// ... 

$composerAutoloaderPaths = array(
    '../vendor/autoload.php', 
    '../../common/vendor/autoload.php' // store common libraries used by multiple projects, currently that's working by adding the directory in set_include_path() 
); 

foreach($composerAutoloaderPaths as $composerAutoloaderPath) 
{ 
    if(file_exists($composerAutoloaderPath)) 
    { 
     require_once $composerAutoloaderPath; 
    } 
    else 
    { 
     // handle the error gracefully 
    } 
} 

// ... 

而且,我使用Zend_Loader_Autoloader這樣的:

<?php // File path: Bootstrap.php 

// ... 

$autoloader = Zend_Loader_Autoloader::getInstance(); 

$autoloader->registerNamespace('Plugin_'); 
$autoloader->registerNamespace('Helper_'); 
// etc. 

// ... 

有什麼擔心使用作曲家和Zend自動加載這個樣子?在bootstrap.php中

回答

2

我經常遇到這個問題,我相信這不是一個實際問題。

IMO最好的辦法就是將作曲家自動加載器包含在public/index.php中,因爲它是在ZF2/3中完成的。這不會改變關於其餘自動加載的東西:https://github.com/zendframework/ZendSkeletonApplication/blob/master/public/index.php#L21

注意:如果您在應用程序中使用了另一個入口點(例如用於cron腳本),則需要添加相同的行(基本上在每個您的應用程序的入口點)。

另外,如果你看一下phpmd的規則,一個給出了這樣的消息:

的文件應當聲明新符號(類,函數,常量,等等),也不會造成其他副作用,或它應該執行具有副作用的邏輯,但不應該同時執行這兩個操作。

因此,聲明在自舉中包含供應商自動加載器可能被認爲是一種弊端(至少似乎是誰寫這個規則和我自己:)誰之間的共同意見)。

1

你可以自動載入供應商這樣的: <?php // File path: Bootstrap.php class Bootstrap extends Zend_Application_Bootstrap_Bootstrap { /** * Inits Vendor */ protected function _initVendor() { require_once APPLICATION_PATH . '/../vendor/autoload.php'; // require_once APPLICATION_PATH . '/new/path/autoload.php'; } ... autoload whatever you want with Zend 1 ... }

我要建議你改用is_file()file_exists(),因爲file_exists當目錄存在返回true,但不是必要的時候.php文件存在

1

我不得不佩服ZF1的適應能力,我們都在10年前去過那裏。 Zend Framework 1.x在其類中充滿了require_once。 隨時可以在Bootstrap.php文件中隨時require_once另一個文件