Search code examples
phpsymfony1functional-testing

Problems with redeclaring classes when using PHP's class_alias in a functional test


I'm using PHP 5.3's class_alias to help process my Symfony 1.4 (Doctrine) forms. I use a single action to process multiple form pages but using a switch statement to choose a Form Class to use.

public function executeEdit(sfWebRequest $request) {
  switch($request->getParameter('page')) {
    case 'page-1':
      class_alias('MyFormPage1Form', 'FormAlias');
    break;
    ...
  }
  $this->form = new FormAlias($obj);
}

This works brilliantly when browsing the website, but fails my functional tests, because when a page is loaded more than once, like so:

$browser->info('1 - Edit Form Page 1')->

  get('/myforms/edit')->
  with('response')->begin()->
    isStatusCode(200)->
  end()->

  get('/myforms/edit')->
  with('response')->begin()->
    isStatusCode(200)->
  end();

I get a 500 response to the second request, with the following error:

last request threw an uncaught exception RuntimeException: PHP sent a warning error at /.../apps/frontend/modules/.../actions/actions.class.php line 225 (Cannot redeclare class FormAlias)

This makes it very hard to test form submissions (which typically post back to themselves).

Presumably this is because Symfony's tester hasn't cleared the throughput in the same way. Is there a way to 'unalias' or otherwise allow this sort of redeclaration?


Solution

  • As an alternate solution you can assign the name of the class to instantiate to a variable and new that:

    public function executeEdit(sfWebRequest $request) {
      $formType;
      switch($request->getParameter('page')) {
        case 'page-1':
          $formType = 'MyFormPage1Form';
        break;
        ...
      }
      $this->form = new $formType();
    }
    

    This doesn't use class_alias but keeps the instantiation in a single spot.