0

I am writing a service that does some stuff with certain query parameter, their names are known.

Since I am not in a controller, I can't use the params plugin.

How can I access query parameters in Zend Framework 2 without using the params plugin? Is there a way to use the params plugin outside of a controller?

1 Answer 1

6

Yes, you can get the query like:

$request = $this->getServiceManager()->get('Request');
$query = $request->getQuery();

More detailed example:

<?php

use Zend\ServiceManager\ServiceManager;
use Zend\ServiceManager\ServiceManagerAwareInterface;

class SomeService implements ServiceManagerAwareInterface
{
    protected $serviceManager;

    public function getServiceManager()
    {
        return $this->serviceManager;
    }

    public function setServiceManager(ServiceManager $serviceManager)
    {
        $this->serviceManager = $serviceManager;
        return $this;
    }

    public function doSomething() 
    {
        $request = $this->getServiceManager()->get('Request');
        $query = $request->getQuery();

        // as well as:
        $params = $this->getServiceManager()->get('ControllerPluginManager')->get('params');
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Vasil Dakov's detailed example could be simplified with a trait: class Class1 { use Zend\ServiceManager\ServiceLocatorAwareTrait; }
I think I understood now how it works. Inside my service, I am now using the ServiceManager & ServiceManagerAwareInterface. As soon as I get my service in another module's controller using $something = $serviceLocator->get('MyService');, I see a white page. From the error log: rewrite or internal redirection cycle while internally redirecting to "/index.php". I know it's a bit vague to ask, but do you have any idea what is happening there?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.