odan / session

A middleware oriented session handler for PHP and Slim 4+
https://odan.github.io/session/
MIT License
58 stars 11 forks source link

Added session aware interface and trait #8

Closed jnessier closed 4 years ago

odan commented 4 years ago

Hi @rjgamer Thanks for the PR.

I'm not sure for what purpose this trait is needed if you use (constructor) dependency injection. Can you tell more about it and give an example?

jnessier commented 4 years ago

AwareInterfaces are needed, if you cannot define the constructor arguments, because the parent class has it already set. And I don't like to change the constructor arguments of child classes (not best practise).

Example:

abstract class BaseController {

   protected $fooBar;

   public function _constructor(FooBar $fooBar) {
       $this->fooBar = $fooBar;
   }
}

class MyController implements SessionAwareInterface {
    use SessionAwareTrait;
}

$container->add(MyController::class, function($container) {
   $fooBar = $container->get(FooBar::class);
   $session = $container->get(SessionInterface::class);

   $controller = new MyController($fooBar);
   $controller->setSession($session);

   return $controller;
}

In combination with Inflectors it is really powerful. Check the examples here: https://container.thephpleague.com/3.x/inflectors/

Psr/Log has also LoggerAwareInterface and LoggerAwareTrait implemented: https://github.com/php-fig/log/tree/master/Psr/Log

What you think? If your lib don't offer these classes, I've to write them myself.

odan commented 4 years ago

Ok this is fine. I have never used this pattern because I always use composition (with constructor dependency injection) and I also try to avoid "extending" classes whenever possible. ;-)