milo / alias-expander
运行时别名展开为完全限定类名。
v1.0.0
2013-07-22 11:22 UTC
Requires
- php: >=5.3.0
Requires (Dev)
- nette/tester: @dev
This package is auto-updated.
Last update: 2024-09-06 08:52:27 UTC
README
它是一个运行时类别名展开工具,用于将其展开为其完全限定名称。简而言之,它是PHP 5.3+中PHP 5.5缺少::class
常量的解决方案,并且是处理注解的辅助工具。
# An ordinary 'use' usage in namespaced code. But how to expand the alias to full class name? use Other\Lib as OL; # in PHP 5.5+ echo OL::class; // 'Other\Lib' # in PHP 5.3+ echo Alias::expand('OL'); // 'Other\Lib' # If the static call is too long for you, wrap it in own function. It will be easy to replace # when upgrade to PHP 5.5. function aliasFqn($alias) { return \Milo\Alias::expand($alias, 1); } # Due to performance, it is good to set writable directory for caching. Alias::getExpander()->setCacheDir('/path/to/tmp'); # If you want to be strict and ensure that alias expands only to defined class name, # set exists checking. This is a debugging advantage against to ::class in PHP 5.5. Alias::getExpander()->setExistsCheck(TRUE); # or Alias::getExpander()->setExistsCheck(E_USER_WARNING); # Expanding an alias in explicitly specified file and line context is useful # for annotations processing. $method = new ReflectionMethod($object, 'method'); Alias::expandExplicit('NS\Alias', $method->getFileName(), $method->getStartLine()); # The Milo\Alias class is only a static wrapper for the Milo\AliasExpander object. # You can use a non-static variation in the same way. $expander = new Milo\AliasExpander; $expander->expand('OL'); $expander->expandExplicit('OL', $file, $line); $expander->setCacheDir('/path/to/tmp'); ...
如果你熟悉Nette框架,有一个准备好的用于与Nette\Cache一起使用的展开器版本。
$storage = new Nette\Caching\Storages\FileStorage('/path/to/tmp'); $expander = new Milo\Nette\AliasExpander($storage);
存在一些限制
- 类似于
namespace First; AliasExpander::expand('Foo'); namespace Second;
的代码可能会导致错误的展开。实现它并不容易,因为PHP标记化和debug_backtrace()只提供行号,而不是列号。这可能在压缩代码中成为一个问题。 self
、static
和parent
关键字不会像PHP 5.5中那样展开,但可以通过使用__CLASS__
、get_called_class()
和get_parent_class()
来轻松解决,而不是使用AliasExpander。
许可证
您可以在新BSD许可证的条款下使用所有文件,或者GNU公共许可证(GPL)版本2或3,或者MIT许可证。
测试
AliasExpander测试是用Nette Tester编写的。运行它们需要两个步骤
# Download the Tester tool composer.phar update --dev # Run the tests vendor/bin/tester tests