2017-04-21 119 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另一个文件