Professional Documents
Culture Documents
// Create an instance of the ReflectionMethod class
$method = new ReflectionMethod(‘Randomizer', get');
echo $method->isConstructor() ? 'the constructor' : 'a regular method‘;
printf("---> Documentation:\n %s\n", var_export($method->getDocComment(), 1));
Reflection is useful for
• Why reverse engineer comments in code?
Easy to generate documentation.
• Unit tests framework: mockup objects, function
test*, etc.
• Automatic serializations of object: your code
defines your data, your objects can be serialized
automatically, converted in JSON, etc.
$reflectionClass = new ReflectionClass('ClassIsData');
$properties = $reflectionClass->getProperties();
$property->getName();
$property->getValue( $instance );
Reflection is useful for
• Annotations, eg. in PHP Unit
function process()
{
$responseBuilder = new ResponseBuilder($this->request);
try {
// eg. get the "Users.getUsers"
$methodToCall = Helper::sanitizeInputVariable('method', $this->request);
list($className, $method) = explode('.',$methodToCall);
$proxy = Proxy::getInstance();
$returnedValue = $proxy->call($className, $method, $this->request );
Registry::get('logger_api')->log($className, $methodName,
$parameterValues
$timer->getTimeMs(),$returnedValue);
return $returnedValue;
}
function loadClassMetadata($className)
{
$reflectionClass = new ReflectionClass($className);
foreach($reflectionClass->getMethods() as $method)
{
$this->loadMethodMetadata($className, $method);
}
}
[...]
Conclusion
• Similar pattern as FrontController / Dispatcher
• One entry point to your Models. You can then add:
– Caching
– Logging
– Authentication
• Eg. If your app is data-centric, the ResponseBuilder could
apply set of filters.
You could for example specify custom filters to be apply to
API calls in the RequestString:
$request = new Request(' method=Analytics.getUsers
&filter_sort=name-desc
&filter_search=(pattern)');
... and use the Proxy class to generate your API
documentation (from the code, and by reverse engineering
your method comments)
Questions?
References
• This pattern is used in the open source Piwik project
http://piwik.org
• View the code on
http://dev.piwik.org/svn/trunk/core/API/
• How to design an API: best practises, concepts
http://piwik.org/blog/2008/01/how-to-design-an-api-best-
practises-concepts-technical-aspects/
• PHP: Reflection – Manual
http://uk.php.net/oop5.reflection
• Declarative Development Using Annotations In PHP
http://www.slideshare.net/stubbles/declarative-development-
using-annotations-in-php