2010-09-13 92 views
12

CodeIgniter是否支持命名空間?PHP中的命名空間CodeIgniter框架

+1

要問的一個更好的問題是爲什麼你需要它們?我通常使用前綴或後綴「命名空間」代碼。例如,$ this-> user_lib或$ this-> user_m意味着你不會與其他任何東西衝突。我真的很想CI支持Controller_Foo但那不是會很快發生: -/ – 2010-09-13 13:11:52

回答

15

命名空間由php支持,而不是框架(codeigniter在您的情況)。如果你使用的命名空間的PHP版本必須> = 5.3.0 笨dosen`t使用命名空間,因爲它被寫入支持PHP 4

+0

這裏找到了一個解決辦法:http://porquero.blogspot.com/2012/03/codeigniter-hmvc-namespaces-part-1.html – 2014-07-24 16:21:01

22

如何獲取命名空間中笨

實際工作,您可以使命名空間與您的應用程序模型中的相對路徑一起工作。這一修改使得負載模型更容易,也可以讓你有接口...

添加到您的application/config/config.php文件

spl_autoload_extensions('.php'); // Only Autoload PHP Files 

spl_autoload_register(function($classname){ 

    if(strpos($classname,'\\') !== false){ 
     // Namespaced Classes 
     $classfile = strtolower(str_replace('\\','/',$classname)); 

     if($classname[0] !== '/'){ 
      $classfile = APPPATH.'models/'.$classfile.'.php'; 
     }    
     require($classfile); 
    } else if(strpos($classname,'interface') !== false){ 
     // Interfaces 
     strtolower($classname); 
     require('application/interfaces/'.$classname.'.php'); 
    } 

}); 

例命名空間類的末尾:

<?php 
// File: application/models/foo/bar.php 
namespace foo; 

class Bar extends \CI_Model implements \Awesome_interface { 

    public $foobar; 

    public function __construct() { 
     return parent::__construct(); 
    } 

    public function getFoobar() { 
     return $this->foobar; 
    } 

    public function setFoobar($val) { 
     $this->foobar = $val; 
    } 

} 

實施例中實例化代碼某處:

重要注意事項:請勿使用內置CI_Loader(例如:$ this-> load-> model(); )

// This will Autoload Your Namespaced Class 
$example = new foo\Bar(); 

或可替換地在你的PHP類(例如頂部:控制器,其他型號),你可以做到這一點...接口

<?php 
... 
use foo\Bar as FooBar; 

... 

// Then you can just do this 
$example = new FooBar(); 

例子:

<?php 
// File: application/interfaces/awesome_interface.php 
interface Awesome_interface { 

    public function getFoobar(); 

} 
+0

在對'spl_autoload_register'方法類進行了一些更改之後加載沒有錯誤。 Thx – 2014-05-08 19:27:07

+0

不客氣。 – 2014-05-12 16:14:56

+0

@TimothyPerez是否有任何其他方式來加載CodeIgniter 3中具有名稱空間的庫? – sam 2017-01-14 13:21:27

0

你可以看看這個:yidas/codeigniter-psr4-autoload

Th ÈLIB定義app爲CI應用程序根,使得在應用程序的每個類可以裝載PSR-4名稱空間:

\app\libraries\MemberService::auth(); 
\app\helpers\ArrayHelper::indexBy($input); 
\app\widgets\StatWidget::run(); 
class Blog_model extends app\core\BaseModel {} 
class Car_model implements app\contracts\CarInterface {} 

示例代碼定義一個類:

<?php 
namespace app\helpers; 
class ArrayHelper 
{ 
    public static function indexBy($input) {} 
} 

https://github.com/yidas/codeigniter-psr4-autoload