Thứ Tư, 6 tháng 3, 2013

Dùng thư viện Zend2.1 trong Kohana framework

Đây là code do mình tự làm (chỉnh sửa từ fuelphp):

Cách dùng rất đơn giản,trong thư mục classes của application tạo file Auto.php rồi paste đoạn code này vào:

<?php
class Auto {
public static $ext;
public static function register($ext1)
{
static::$ext = $ext1;
spl_autoload_register('Auto::load', true, true);
}
public static function load($class)
{
// deal with funny is_callable('static::classname') side-effect
if (strpos($class, 'static::') === 0)
{
// is called from within the class, so it's already loaded
return true;
}

$loaded = false;
$class = ltrim($class, '\\');

$path = static::$ext.static::class_to_path($class);

if (file_exists($path))
{
include $path;
$loaded = true;
}

return $loaded;
}
protected static function class_to_path($class, $psr = false)
{
$file = '';
if ($last_ns_pos = strripos($class, '\\'))
{
$namespace = substr($class, 0, $last_ns_pos);
$class = substr($class, $last_ns_pos + 1);
$file = str_replace('\\',DIRECTORY_SEPARATOR, $namespace).DIRECTORY_SEPARATOR;
}
$file .= str_replace('_', DIRECTORY_SEPARATOR, $class).'.php';
if ( ! $psr)
{
$file = strtolower($file);
}

return $file;
}

}
?>



Trước khi bạn muốn load 1 class bạn chỉ cần thêm vào :


Auto::register('ten_folder_chua_thu_vien_do');

Ví dụ:

Bạn muốn sủ dụng thư viện Zend2.1,down thư mục Zend bỏ vào trong folder vendor trong application.Trong Controller trước khi bạn muốn dùng 1 class nào của Zend ,bạn chỉ cần viết:


Auto::register(APPPATH.'vendor/');
$content = array(
'author' => 'Steve',
'categories' => array(
'PHP', 'Zend', 'JavaScript'
)
);
$json = \Zend\Json\Json::encode($content);
var_dump($json);

Nếu bạn thấy mảng trong $content biến thành chuỗi json là bạn đã thành công rồi đó
Các bạn góp ý nhe.

1 nhận xét:

  1. Hay nhỉ,chắc có thể autoload mọi thư viện có namespâce luôn bạn nhỉ

    Trả lờiXóa