Dynamically Calling Methods - Inheritance/PHP5

    Date: 07/11/07 (PHP Community)    Keywords: no keywords

    Right, I've got an interestingstupid problem. I have a controller base class:



    abstract class BaseController {

      final public function execute($action) {
         $action = $action."Action";
         if (method_exists($this, $action)) {
             return $this->{$action};
        } else {
            return $this->defaultAction();
        }
     }

    public function defaultAction() {
    return 'This should be overridden';
    }
    }



    Which I then inherit for page controllers:


    class SomePageController extends BaseController {
    public function thingAction() {
    return "thinging";
    }
    }



    Of course, the problem is that the execute($action) function is only in the scope of the abstract base class, so the $this in question is actually an instance of a PageControllerBase not a SomePageController and thus $actionAction never exists. So it's always the defaultAction that is executed.

    Is there anyway I can code the execute() handler so it can route to the right action handler in an inherited sub-class without re-implementing the execute handler in every derived class?


    Actually, the problem turns out to be that I didn't have the line:


    if (method_exists($this, $action)) {


    I had

    if (method_exists($this, $action."Action")) {


    So I was looking for thingActionAction() which of course, doesn't exist.

    And also I was actually writing code in SomeOtherPageController, which extended SomePageController, but still instantiating SomePageController which didn't have listenAction() which was the action I was trying to execute.

    Let that be a lesson to me: Don't code and watch TV at the same time.

    Source: http://community.livejournal.com/php/576070.html

« Trouble || Step in the right direction »


antivirus | apache | asp | blogging | browser | bugtracking | cms | crm | css | database | ebay | ecommerce | google | hosting | html | java | jsp | linux | microsoft | mysql | offshore | offshoring | oscommerce | php | postgresql | programming | rss | security | seo | shopping | software | spam | spyware | sql | technology | templates | tracker | virus | web | xml | yahoo | home