Example of StrictInterceptor is located in example/misc/stric. Each class file, a configuration file, and directory composition become the next.
example/misc/strict/ +-- classes/ | +-- sample/ | +-- StrictAnnotationFactory.php | +-- StrictException.php | +-- StrictInterceptor.php +-- execute.phpThe following three classes located in a clases directory are needed in order to use StrictInterceptor.
StrictInterceptor is Interceptor which performs a type check about a method argument and a return value at the time of a method call. Specification of the type of a method argument and a return value is set up by Annotation.
<?php class Calc { /** * @param numeric $a * @param numeric $b * @return integer */ public function add($a, $b) { return $a + $b; } }
When the specified type is a class it is checked whether the instance belonging to the class. If the class of the specified model does not exist, it checks by using the function of the name which added the "is_" character string to the specified type. For example, an is_integer function is used when type specification is integer. Moreover, two or more specification of a type can be specified by dividing by "|". OR verification is applied when two or more types are specified.
Let's create following Hoge class as an example.
- classes/sample/Hoge.php
<?php namespace sample; class Hoge { /** * @param numeric $a checked with is_numeric function * @param string $b checked with is_string function * @return object checked with is_object function */ public function foo($a, $b) { return new StdClass; } /** * @param sample\Huga $a Huga class or not, or checked with is_subclass_of function * @param mixed $b type check is not performed * @return null|sample\Huga checked with is_null function * or Huga class or not, or checked with is_subclass_of function */ public function bar(sample\Huga $a, $b) { return null; } } class Huga {}
An execution script becomes the next. The automatic aspect of StrictInterceptor is applied to the Hoge class.
- sample.php
<?php require_once(dirname(dirname(dirname(__FILE__))) . '/example.inc.php'); use seasar\container\S2ApplicationContext as s2app; s2app::import(dirname(__FILE__) . '/classes'); s2app::registerAspect('StrictInterceptor', '/Hoge/'); $hoge = s2app::get('Hoge'); $obj = $hoge->foo(1, 'abc'); $obj = $hoge->bar(new sample\Huga, 100); try { $obj = $hoge->foo(1, 2); } catch(StrictException $e) { print $e->getMessage() . PHP_EOL; }
In execution of the 2nd foo method, since the 2nd argument is not a character string, StrictException thrown. A message "argument[1] type unmatch. expected string" will be displayed.
© Copyright The Seasar Foundation and the others 2005-2010, all rights reserved. |