Is anti-pattern to handle redirections and view variables within Cake Components?

  Kiến thức lập trình

I am working on a project with CakePHP 2.x and I found 3 Controllers that share the same logic but some part of that logic is to set view variables and redirections.

class ControllerA
{
  public function method1()
  {
    // shared logic
    if ($some_condition)
    {
      $this->redirect(['action' => 'some_action_from_same_controller'];
    }

    $this->set('view_var', $value);
  }
}

class ControllerB
{
  public function method1()
  {
    // shared logic
    if ($some_condition)
    {
      $this->redirect(['action' => 'some_action_from_same_controller'];
    }

    $this->set('view_var', $value);
  }
}
// Same for a third controller.

I want to take advantage of Cake Components and in the docs appears that the controller is passed to the component. So i think I might be able to just do the following:

class MyComponent
{
  public function initialize(Controller $controller)
  {
    $this->controller = $controller;
  }

  public function method1()
  {
    if ($some_condition)
    {
      $this->controller->redirect(['action' => 'some_action_from_same_controller']);
    }

    $this->controller->set('view_variable', $value);
  }
}

I assume my controllers would look like this:

class ControllerA
{
  public function method1()
  {
    $this->MyComponent->method1();
  }
}

class ControllerB
{
  public function method1()
  {
    $this->MyComponent->method1();
  }
}

I look up for an approach like this in the same codebase and in other projects but I did not find anyhting like it and I am afraid I may be using an anti-pattern(?)

I thought of using just one controller, but the views (even though they share the same view vars) are different.

Is there a “better” way to accomplish this or should I go ahead and use a component?

LEAVE A COMMENT