我的代码有奇怪的问题。我的代码几乎与下面的代码相同(我没有提供实际的代码b`z,因为它是一个具有大量动态生成(基于路径路由等的类,即框架)的大型库)。
该守则解释说:
ClassA表示当前路由对象。包含控制器、路由字符串等。
ScriptAClassAction是dispatcher,它检查路由是否具备执行所需的一切,以及控制器是否存在$!empty(reflection),以及是否存在控制器$reflection->hasMethod('hello')中的操作。
在我的世界中,如果这两个条件都意味着(而不是),则应该触发父级if,或者其他条件应该被触发,这意味着检查哪些检查失败了。在执行时,我看到第一个检查通过(我认为这是PHP中的一个bug ),然后触发,然后触发第二个if。
我认为这可能是PHP中的一个bug,但我非常怀疑。有人看到我早上1点50分错过的东西了吗?
PHP5.3.27带有启用的xDebug(没有其他扩展)&Apache2.2.25(我认为Apache在这里无关紧要,但是.),x86 7家庭高级版
ClassA.php
class A
{
public function init()
{
print 'Init called';
}
public function preDispatch()
{
print 'Predispatch called';
}
public function indexAction()
{
print 'Hello world';
}
public function postDispatch()
{
print "Post dispatch";
}
}ScriptAClassAction.php
require 'ClassA.php';
$class = new A();
$reflection = new ReflectionClass($class);
if (!empty($reflection) && $reflection->hasMethod('indexAction')) {
if ($reflection->hasMethod('init')) $class->init($request, $response); //Prints 'Init called'
if ($reflection->hasMethod('preDispatch')) $class->preDispatch(); // 'Predispatch called'
$class->indexAction();
if ($reflection->hasMethod('postDispatch')) $class->postDispatch(); // 'post dispatch called'..
} else {
if (!$reflection) // I know this might not be the best check but..
print "Not a valid class supplied";
if (false == $reflection->hasMethod('indexAction')) // True trigger
print "Supplied class does not have any manners and does not greet you :D";
// This is the expected output and it should be the only output
}**产出**
因为它叫做预先发送,称为Postdospatch,称为供应类,它没有任何礼貌,也没有问候您:D
发布于 2013-08-25 07:29:13
在if语句中添加括号将解决这个问题。另外,您不必测试$reflection变量是否为空。它将永远是一个实例。
正如@traq所提到的,最好创建接口来标识具有特定行为的类。
interface DispatchAware {
public function preDispatch();
public function postDispatch();
}
class A implements DispatchAware { ... }现在,您不必检查可能存在的所有方法。当一个类实现一个接口时,您就会知道它是存在的。
您的分派代码现在看起来可能如下所示:
$action = 'indexAction';
$a = new A();
if ($a instanceof DispatchAware) {
$a->preDispatch();
}
try {
$r = new ReflectionClass($a);
$method = $r->getMethod($action);
$method->invoke($a, $request, $response);
} catch (Exception $e) {
methodNotFoundError();
}
if ($a instanceof DispatchAware) {
$a->postDispatch();
}我还删除了init()方法。原因是控制器类型对象通常不需要保持状态。这就是为什么$request和$response作为参数传递给action方法的原因。
https://stackoverflow.com/questions/18424623
复制相似问题