目錄
開始
mkdir annotation && cd annotation
mkdir -p module/Base
vim module/Base/Description.php
<?php
namespace Base;
class Description
{
public $desc = 'default';
}
vim composer.json
{
"autoload": {
"psr-4": {
"Base\\": "module/Base/"
}
}
}
composer update
關于命名空間 更多參考PHP學習 之 namespace
vim index.php
<?php
require "vendor/autoload.php";
use Base\Description;
var_dump(new Description());
關于自動加載 更多參考PHP學習 之 autoload
- 測試
php index.php
object(Base\Description)#3 (1) {
["desc"]=>
string(7) "default"
}
關于PHP環(huán)境搭建 更多參考PHP開發(fā) 之 開發(fā)環(huán)境
注解
composer require doctrine/annotations
vim module/Base/Description.php
<?php
namespace Base;
/**
* @Annotation
*/
class Description
{
public $desc = 'default';
}
關于doctrine/annotations 更多參考Doctrine Annotations
類注解
vim index.php
<?php
use Doctrine\Common\Annotations\AnnotationRegistry;
use Doctrine\Common\Annotations\AnnotationReader;
$loader = require __DIR__ . '/vendor/autoload.php';
AnnotationRegistry::registerLoader(array($loader, 'loadClass'));
use Base\Description;
/**
* @Description(desc="class")
*/
class AnnotationDemo
{
public function __construct()
{
$annotationReader = new AnnotationReader();
$reflectionClass = new ReflectionClass(get_class($this));
/**
* class annotations
*/
$classAnnotations = $annotationReader->getClassAnnotations($reflectionClass);
foreach ($classAnnotations as &$classAnnotation)
{
var_dump($classAnnotation);
}
}
}
$annotationDemo = new AnnotationDemo();
關于PHP反射 更多參考PHP: 反射
- 測試
php index.php
object(Base\Description)#13 (1) {
["desc"]=>
string(5) "class"
}
屬性注解
vim module/Base/Di.php
<?php
namespace Base;
/**
* @Annotation
*/
class Di
{
public $class = null;
}
vim index.php
<?php
# 省略了未修改代碼
use Base\Description;
use Base\Di;
/**
* @Description(desc="class")
*/
class AnnotationDemo
{
/**
* @Di(class="Base\Description")
*/
private $desc;
public function __construct()
{
# 省略了未修改代碼
/**
* property annotations
*/
foreach ($reflectionClass->getProperties() as &$property)
{
$propertyAnnotations = $annotationReader->getPropertyAnnotations($property);
foreach ($propertyAnnotations as &$propertyAnnotation)
{
/**
* @var Di $propertyAnnotation
*/
$reflectionClass = new ReflectionClass($propertyAnnotation->class);
$property->setAccessible(true);
$property->setValue($this, $reflectionClass->newInstance());
}
}
}
}
$annotationDemo = new AnnotationDemo();
var_dump($annotationDemo);
關于ReflectionProperty 更多參考PHP: ReflectionProperty
- 測試
php index.php
object(AnnotationDemo)#3 (1) {
["desc":"AnnotationDemo":private]=>
object(Base\Description)#9 (1) {
["desc"]=>
string(7) "default"
}
}