Skip to content

Instantly share code, notes, and snippets.

@guiwoda
Forked from anonymous/MyMiddleware.php
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guiwoda/505cc8e34f5c04edafae to your computer and use it in GitHub Desktop.
Save guiwoda/505cc8e34f5c04edafae to your computer and use it in GitHub Desktop.
<?php
namespace Acme;
use Symfony\Component\HttpKernel\HTTPKernelInterface;
use Psr\Http\Message\RequestInterface;
class MyMiddleware implements HTTPKernelInterface {
private $kernel;
public function __construct(HTTPKernelInterface $kernel)
{
$this->kernel = $kernel;
}
public function handle(RequestInterface $request, $type = self::MASTER_REQUEST, $catch = true)
{
// One option
$myRequest = new MyRequestDecorator($request);
// Another Option
$myRequest = MyMutableRequest::createFrom($request);
$myRequest->setQueryParams(['foo' => 'bar']);
return $this->kernel->handle(
$myRequest,
$type,
$catch
);
}
}
<?php
namespace Acme;
use Psr\Http\Message\RequestInterface;
class MyMiddlewareConsumer {
public function doSomeRequestMagic(MyRequestDecorator $request)
{
// Here I expect a modified request
}
public function doMoreRequestMagic(MyMutableRequest $request)
{
// Here I can modify the request myself
}
public function doEvenMoreRequestMagic(WritableRequestInterface $request)
{
// Here I can modify the request myself, without coupling to (a|my) concrete implementation
}
public function doSomethingNotRelated(RequestInterface $request)
{
// Here I can't modify the request
}
}
<?php
namespace Acme;
use Psr\Http\Message\RequestInterface;
class MyMutableRequest implements RequestInterface {
public static function createFrom(RequestInterface $request)
{
$myRequest = new static;
$myRequest->setQueryParams($request->getQueryParams());
$myRequest->setProtocolVersion('1.0');
// ...
return $myRequest;
}
public function setQueryParams(array $params)
{
$this->queryParams = $params;
}
// implement any other setters as needed, and missing methods...
}
<?php
namespace Acme;
use Psr\Http\Message\RequestInterface;
class MyRequestDecorator implements RequestInterface {
private $request;
public function __construct(RequestInterface $request)
{
$this->request = $request;
}
public function getQueryParams()
{
return ['foo' => 'bar'];
}
// Act as a proxy for all other methods...
}
<?php
namespace Acme;
use Psr\Http\Message\RequestInterface;
interface WritableRequestInterface extends RequestInterface {
// You could even decouple your own code with this one, without forcing it to others
public function setQueryParams(array $params);
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment