Search code examples
phpoopcakephpcomponentsmiddleware

How a custom component can be imported in Cakephp MiddleWare Class?


I have a generic OAuthComponent with a

namespace App\Controller\Component

my Middleware Class has a namespace

namespace App\Middleware;

How can I use a custom Component in the Middleware?


Solution

  • You can't because a component relies on the controller. Loading a component in a middleware is completely wrong and goes against the architecture and design patterns of the framework.

    Cake < 3.6

    Refactor the component in an an object that has no other dependency than request and response and then create a middleware that will use this object.

    Cake >= 3.6 & 4.0

    It looks like you want to do something with auth, so for newer versions of CakePHP use the identifiers of the authentication plugin instead of using an auth component at all. The plugin implements a middleware and the specific authentication mechanics are abstraced into identifiers.

    https://book.cakephp.org/authentication/2/en/index.html