0

It is stated in the ZF2 documentation, as well as by Matthew Weier O'Phinney's blog, that:

Many developers want to stick this in their MVC application directly, in order to have pretty URLs. However, the framework team typically recommends against this. When serving APIs, you want responses to return as quickly as possible, and as the servers basically encapsulate the Front Controller and MVC patterns in their design, there's no good reason to duplicate processes and add processing overhead.

It is recommended that you put the server endpoints in the public directory structure. For example, you might have /public/some-api.php that instantiates and runs the Zend RPC Server. But I have already created this dope module in which I have a bunch of classes and a config file that lays out the dependency injection, factories, etc for creating the classes.

Soo... how do I leverage that code in my RPC server, without putting it into a MVC controller?

Thanks! Adam

1 Answers1

1

Here is how I did it. I have this broken out into a few files, but you can put all this in your public root directory, something like rpc-service.php:

use Zend\ServiceManager\ServiceManager,
    Zend\Mvc\Service\ServiceManagerConfig;

class Bootstrap {
    /** @var  ServiceManager */
    private static $serviceManager;

    private static function _go() {
        chdir(dirname(__DIR__));

        require __DIR__ . '/../init_autoloader.php';

        $config = include __DIR__ . '/../config/application.config.php';

        $serviceManager = new ServiceManager(new ServiceManagerConfig());
        $serviceManager->setService('ApplicationConfig', $config);
        $serviceManager->get('ModuleManager')->loadModules();

        self::$serviceManager = $serviceManager;
    }

    /**
     * @return ServiceManager
     */
    public static function getServiceManager() {
        if (!self::$serviceManager)
            self:: _go();

        return self::$serviceManager;
    }
}

$sm = Bootstrap::getServiceManager();

use Zend\Json\Server\Server,
    Zend\Json\Server\Smd,

$jsonRpc = new Server();
$jsonRpc->setClass($sm->get('Some\Class'));
$jsonRpc->getRequest()->setVersion(Server::VERSION_2);

if ($_SERVER['REQUEST_METHOD'] == 'GET') {
    echo $jsonRpc->getServiceMap()->setEnvelope(Smd::ENV_JSONRPC_2);
}
else {
    $jsonRpc->handle();
}

As you can see, I'm using the Service Manager! Yay. All is right in the world.