2012-02-05 48 views
0

我在我的/應用程序文件夾下有一個名爲「grids」的文件夾。現在我的類名是App_Grid_CustomGrid。我怎樣才能自動加載這些類在網格文件夾下?我在Zend_Application之前嘗試了index.php中的以下代碼。但它沒有奏效。代碼找不到CustomGrid類。將應用程序的子目錄添加到自動加載器

require_once 'Zend/Loader/Autoloader/Resource.php'; 

$resourceLoader = new Zend_Loader_Autoloader_Resource(array(
     'basePath' => APPLICATION_PATH, 
     'namespace' => '', 
)); 
$resourceLoader->addResourceType('grid', 'grids', 'Grid'); 

回答

2

我用下面的方法在BootStrap.ini中存儲的文件夾在我的應用程序根目錄自動加載自定義類(定製,以滿足您的需求):

protected function _initNamespaces() 
{   
    $resourceLoader = new Zend_Loader_Autoloader_Resource(array(
     'basePath' => APPLICATION_PATH, 
     'namespace' => '', 
     'resourceTypes' => array(
       'grid' => array(
        'path'  => 'grids/', 
        'namespace' => 'Grid', 
       ), 
       'example' => array(
        'path'  => 'example_folder/', 
        'namespace => 'Example' 
       ) 
    ));   
} 

離開命名空間空白允許你從類名的開頭省略App_。我單獨做這個,我使用庫文件夾中的App_來定製類和插件。可以使用上述方法加載多個名稱空間,只需將其他數組添加到resourcesType參數中即可。

應用結構如下:

|Project 
    |-Application 
     |-grids 
      |-Test.php 
     |-configs 
     |-controllers 
     |-models 
     |-views 
     |-Bootstrap.php 
    |-Docs 
    |-Library 
    |-Public 
    |-.zfproject.xml 

test.php的是這樣的:

<?php 
class Grid_Test 
{ 

    /** 
    * Return sum of two variables 
    * 
    * @param int $x 
    * @param int $y 
    * @return array 
    */ 
    public function add($x, $y) 
    { 
     return $x + $y; 
    } 
} 
+0

謝謝!我必須爲每個模塊編寫這個Zend_Loader_Autoloader_Resource行嗎? – 2012-02-07 18:35:39

+0

不可以。以上Zend_Loader_Autoloader_Resource示例允許您告訴應用程序註冊一個名稱空間數組 - 然後您可以在自定義類中使用。我已經使用'example'更新了示例,以說明如何爲呼叫添加其他名稱空間。 – Sjwdavies 2012-02-08 09:53:01

1

嘗試:

$resourceLoader = new Zend_Loader_Autoloader_Resource(array(
    'basePath' => APPLICATION_PATH, 
    'namespace' => 'App', 
)); 
$resourceLoader->addResourceType('grid', 'grids/', 'Grid'); 

我認爲這是行不通的,因爲它需要,因爲它的前綴是App_,並有在目錄的結尾,因此它可能沒有尾隨斜線命名空間一直在尋找gridsCustomGrid.php以及。