GithubHelp home page GithubHelp logo

laminas-controller-injector's Introduction

Laminas Controller Injector

Description

The core feature of this “plugin” is the ability to set parameters for controller methods. Primarily to pass the value of a variable of a route directly to the method at the dispatch event as an argument. The new AbstractInjectorController must be used for this usage.

In addition, with the new dispatcher you can also do without the “Action” postfix for these methods.

Requirements

  • PHP 8.1 or above
  • Laminas MVC 3.7.0 or above

Installation

Use composer to install the package:

composer require nubox/laminas-controller-injector

Activate Plugin in our Laminas Application

return [
    // Retrieve list of modules used in this application.
    'modules' => [
        ...,
        Laminas\Mvc\Injector\Module::class, // or 'Laminas\Mvc\Injector'
    ],
    ...
];

Usage

Suppose you have a controller that looks like this:

class MyController extends AbstractInjectorController
{ 
    public function myMethod(string $param) { 
        // ... 
    } 
}

You can map routes to this controller method using the format controller::method and pass parameters from the routes directly into the method:

return [
    'router' => [
        'routes' => [
            'my-route' => [
                'type' => Laminas\Router\Http\Segment::class,
                'options' => [
                    'route' => '/my-route/:param',
                    'defaults' => [
                        'controller' => MyController::class,
                        'action' => 'myMethod'
                    ]
                ]
            ]
        ]
    ],
];

In the example above, the :param placeholder in the route gets passed directly as the $param argument to myMethod().

AbstractInjectorController

The provided \Laminas\Mvc\Injector\Controller\AbstractInjectorController is required as Controller extension. It matches the given parameter values into the requested action. The same variable name is required.

As soon as the AbstractInjectorController is used, in addition to the route parameters, objects from the ServiceManager are also injected into the corresponding controller method - regardless of the route. This reduces the processes necessary to access a service from the ServiceManager.

The respective request can also be injected as a complete request object.

class MyController extends AbstractInjectorController
{
    public function serviceParameter(DemoService $demoService): Response
    {
        $response = new Response();
        $response->setContent($demoService->getValue());

        return $response;
    }
}

Available ArgumentResolver -> (configurable controller_argument_resolver)

Every argument of a controller method is analyzed and can be determined by the activated ArgumentResolver. The following ArgumentResolvers are activated by default. However, additional ArgumentResolvers can also be added.

Activated by default:

  • IntegerArgumentResolver - inject a int, parsed from Route parameters (int required)
  • StringArgumentResolver - inject a string , parsed from Route parameters (no typehint or string required)
  • RequestArgumentResolver - inject the responding Request object into the method (Request required)
  • ServiceArgumentResolver - inject an object from the container (ServiceManager) (explicit object Typehint required)
return [
    /**
     * each resolver need to implement ArgumentResolverInterface:class
     */
    'controller_argument_resolver' => [
        StringArgumentResolver::class,
        IntegerArgumentResolver::class,
        RequestArgumentResolver::class,
        ServiceArgumentResolver::class,
    ],
];

Normally you need a corresponding type hint to determine the correct ArgumentResolver. In the event that no suitable type can be found, you can use the MarkUp interface NonTypeArgumentResolverInterface for your own ArgumentResolver. this would then also be “queried” in such a case.

Suggestion

Use nubox/laminas-router-attributes for reduce configuration overhead with symfony route attributes.

class MyController extends AbstractInjectorController
{ 
    #[Route(path: 'calc-optional/{operand1}/{operand2?100}', name: 'calc-optional-route')]
    public function calculateWithRouteDefault(int $operand1, int $operand2 = 100): Response
    {
        $response = new Response();
        $response->setContent($operand1 * $operand2);

        return $response;
    }
    
    #[Route(path: 'default', name: 'default-route')]
    public function somedefaults(Request $request, string $default = 'defaults'): Response
    {
        $response = new Response();
        $response->setContent($request->getUri()->getPath() . ' - ' . $default);

        return $response;
    }
}

laminas-controller-injector's People

Contributors

nusphere avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.