0

I am building my website in Slim 3 MVC framework.I need to call some commonly used functions for controller (Eg: For Alias of page title I am using a function called function getAlias(){.....}).

Where I have to create those functions? How can I call inside controllers?

Matt
  • 14,906
  • 27
  • 99
  • 149
Sandeep Bhaskaran
  • 621
  • 1
  • 7
  • 14

1 Answers1

0

There's a number of ways to do this. If the functions have no side effects, then one option would be to have a utilities class with static methods in it it.

Another option would be to extend all your route actions from a common class and use that:

// CommonAction.php
class CommonAction
{
    protected function getAlias() { }
}

// HomeAction.php
class HomeAction extends CommonAction
{
    public function __construct(/*dependencies here*/) { }

    public function __invoke($request, $response, $args) {
        // route action code here
        return $response;
    }
}

// index.php
$app = new Slim\App(require('settings.php'));

$container = $app->getContainer();
$container[HomeAction::class] = function ($c) {
    return new HomeAction(/*dependencies*/);
}

$app->get('/', HomeAction::class);

$app->run();

If the functionality is part of your domain layer, then inject those classes into your route actions as a dependency.

Rob Allen
  • 12,643
  • 1
  • 40
  • 49