Cakephp, PHP

Import bundle có namespace vào cakephp 2

Namespaces in vendor files and Cake2.x


Như link trên, cakephp 2 không hỗ trợ namespace. Do đó nên ta cần import file vào.

spl_autoload_register(function ($class) {
foreach (App::path('Vendor') as $base) {
$path = $base . str_replace('\\', DS, $class) . '.php';
if (file_exists($path)) {
include $path;
return;
}
}
});

Dòng lệnh trên sẽ cho vào cuối file config/bootstrap.php. Tiếp theo ở nơi cần dùng bundle, ta import file vào:

// APP/Lib/MyClass.php
App::import('Vendor', 'PackageName', array('file' => 'PackageName/SubFolder/ClassName.php'));
class MyClass {
protected $_Engine;
public function __construct($settings) {
parent::__construct($settings);
if (!class_exists('PackageName\SubFolder\ClassName')) {
throw new RuntimeException('Your desired vendor library cannot be found');
}
$this->_Engine = new PackageName\SubFolder\ClassName($settings);
}
}

Chi tiết hơn có thể xem link trên.