I want to use a standalone Symfony2 Routing component in my small site. I've created this according to documentation and some examples:
$request = Request::createFromGlobals();
$routeTest = new Symfony\Component\Routing\Route('/route-test', array('controller' => 'test'));
$routes = new Symfony\Component\Routing\RouteCollection();
$routes->add('test', $routeTest);
$context = new Symfony\Component\Routing\RequestContext();
$context->fromRequest($request);
$matcher = new Symfony\Component\Routing\Matcher\UrlMatcher($routes, $context);
$matcher->match($request->getPathInfo());
I don't understand how I should call my controller test, that I've passed to the Route constructor. As a result I want to get something like Silex Route matching:
$app->get('/hello/{name}', function($name) use($app) {
return 'Hello '.$app->escape($name);
});
And sorry for my english...
$matcher->match() returns[1] the attributes of the matching route[2] (including a special _route attribute containing the route name [3]).
The controller default is included in the attributes too, so you can easily access it and then use something like call_user_func to call the controller:
// ...
$attributes = $match->match($request->getPathInfo());
$controllerResult = call_user_func($attributes['controller']);
Related
Hi Folks i upgrading my slim framework from slim 2 to slim 4 for older project
for one route i added the one value before route using slim 2 slim.before in index.php
example code:
$app->hook('slim.before', function () use ($app) {
$env = $app->environment();
$path = $env['PATH_INFO'];
// spliting the route and adding the dynamic value to the route
$uriArray = explode('/', $path);
$dynamicvalue = 'value';
if(array_key_exists($uriArray[1], array)) {
$dynamicvalue = $uriArray[1];
//we are trimming the api route
$path_trimmed = substr($path, strlen($dynamicvalue) + 1);
$env['PATH_INFO'] = $path_trimmed;
}
});
i read about the add beforemiddleware but cannot able find correct way to add it and i cannot able to find the replacement for $app->environment();
i want to append the dynamic value directly to route
for example
i have one route like this
https://api.fakedata.com/fakeid
by using the above route splitting code i appending the value route using slim.before in slim 2
for example take the dynamic value as test
the route will be
https://api.fakedata.com/test/fakeid
the response of the both api will be same we want to just add value to the route
can any one help me how to do with slim 4
I assume you need to and PATH_INFO to the environment so you can later refer to it in the route callback. You can add a middleware to add attributes to the $request the route callback receives:
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
use Slim\Psr7\Response;
class PathInfoMiddleware {
public function __invoke(Request $request, RequestHandler $handler) : Response {
$info = 'some value, path_trimmed for example...'; // this could be whatever you need it to be
$request = $request->withAttribute('PATH_INFO', $info);
return $handler->handle($request);
}
}
// Add middleware to all routes
$app->add(PathInfoMiddleware::class);
// Use the attribute in a route
$app->get('/pathinfo', function(Request $request, Response $response){
$response->getBody()->write($request->getAttribute('PATH_INFO'));
return $response;
});
Now visiting /pathinfo gives the following output:
some value, path_trimmed for example...
I have mvc php cms like this folder structure:
application
---admin
--------controller
--------model
--------view
--------language
---catalog
--------controller
------------------IndexController.php
--------model
--------view
--------language
core
--------controller.php
//...more
public
--------index.php
vendor
I install symfony/router component for help my route url using composer json:
{
"autoload": {
"psr-4": {"App\\": "application/"}
},
"require-dev":{
"symfony/routing" : "*"
}
}
Now with route documents I add this code for routing in index.php:
require '../vendor/autoload.php';
use Symfony\Component\Routing\Matcher\UrlMatcher;
use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\Route;
$route = new Route('/index', array('_controller' => 'App\Catalog\Controller\IndexController\index'));
$routes = new RouteCollection();
$routes->add('route_name', $route);
$context = new RequestContext('/');
$matcher = new UrlMatcher($routes, $context);
$parameters = $matcher->match('/index');
In My IndexController I have :
namespace App\Catalog\Controller;
class IndexController {
public function __construct()
{
echo 'Construct';
}
public function index(){
echo'Im here';
}
}
Now in Action I work in this url: localhost:8888/mvc/index and can't see result : Im here IndexController.
How do symfony routing url work and find controller in my mvc structure? thank for any practice And Help.
The request context should be populated with the actual URI that's hitting the application. Instead of trying to do this yourself you can use the HTTP Foundation package from symfony to populate this:
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\RequestContext;
$context = new RequestContext();
$context->fromRequest(Request::createFromGlobals());
It's also documented here: https://symfony.com/doc/current/components/routing.html#components-routing-http-foundation
After the matching ($parameters = $matcher->match('/index');) you can use the _controller key of the parameters to instantiate the controller and dispatch the action. My suggestion would be to replace the last \ with a different symbol for easy splitting, like App\Controller\Something::index.
You can then do the following:
list($controllerClassName, $action) = explode($parameters['_controller']);
$controller = new $controllerClassName();
$controller->{$action}();
Which should echo the response you have in your controller class.
I'm using the Symfony Routing components standalone, i.e. not with the Symfony framework. Here's my bare-bones code I'm playing with:
<?php
$router = new Symfony\Component\Routing\RouteCollection();
$router->add('name', new Symfony\Component\Routing\Route(/*uri*/));
// more routes added here
$context = new Symfony\Component\Routing\RequestContext();
$context->setMethod(/*method*/);
$matcher = new Symfony\Component\Routing\Matcher\UrlMatcher($router, $context);
$result = $matcher->match(/*requested path*/);
Is there a way to cache the routes, so I don't need to run all the add() calls on every page load? (See for example FastRoute.) I believe there is caching when using the full Symfony framework, can that be implemented easily here?
The Symfony Routing Component documentation contains an example of how to easily enable the cache: The all-in-one Router
Basically your example can be reworked like the following:
// RouteProvider.php
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\Route;
$collection = new RouteCollection();
$collection->add('name', new Route(/*uri*/));
// more routes added here
return $collection;
// Router.php
use Symfony\Component\Config\FileLocator;
use Symfony\Component\Routing\RequestContext
use Symfony\Component\Routing\Loader\PhpFileLoader;
$context = new RequestContext();
$context->setMethod(/*method*/);
$locator = new FileLocator(array(__DIR__));
$router = new Router(
new PhpFileLoader($locator),
'RouteProvider.php',
array('cache_dir' => __DIR__.'/cache'), // must be writeable
$context
);
$result = $router->match(/*requested path*/);
So the title describes my problem pretty well I think, but let me explain why I want to do this as theremight be an other solution to my problem that I haven't thought about.
Let's say that I have a route specifying the class of the object it will patch:
Route::patch('{class}/{id}', array(
'as' => 'object.update',
function ($class, $id) {
$response = ...;
// here I want to call the update action of the right controller which will
// be named for instance CarController if $class is set to "car")
return $response;
}
));
This is something pretty easy to do with $app->make($controllerClass)->callAction($action, $parameters); but doing it this way won't call the filters set on the controller.
I was able to do it with laravel 4.0 with the callAction method, passing the app and its router, but the method has changed now and the filters are called in the ControllerDispatcher class instead of the Controller class.
If you have routes declared for your classes then you may use something like this:
$request = Request::create('car/update', 'POST', array('id' => 10));
return Route::dispatch($request)->getContent();
In this case you have to declare this in routes.php file:
Route::post('car/update/{id}', 'CarController#update');
If you Use this approach then filters will be executed automatically.
Also you may call any filter like this (not tested but should work IMO):
$response = Route::callRouteFilter('filtername', 'filter parameter array', Route::current(), Request::instance());
If your filter returns any response then $response will contain that, here filter parameter array is the parameter for the filter (if there is any used) for example:
Route::filter('aFilter', function($route, $request, $param){
// ...
});
If you have a route like this:
Route::get('someurl', array('before' => 'aFilter:a_parameter', 'uses' => 'someClass'));
Then the a_parameter will be available in the $param variable in your aFilter filter's action.
So I might have found a solution to my problem, it might not be the best solution but it works. Don't hesitate to propose a better solution!
Route::patch('{class}/{id}', array(
'as' => 'object.update',
function ($class, $id) {
$router = app()['router']; // get router
$route = $router->current(); // get current route
$request = Request::instance(); // get http request
$controller = camel_case($class) . 'Controller'; // generate controller name
$action = 'update'; // action is update
$dispatcher = $router->getControllerDispatcher(); // get the dispatcher
// now we can call the dispatch method from the dispatcher which returns the
// controller action's response executing the filters
return $dispatcher->dispatch($route, $request, $controller, $action);
}
));
I want to replace the emailtemplates router to contactpoints from the following URL
http://localhost/app_dev.php/config/workflow/configset-72/partner_site/emailtemplates
My routing pattern is: /config/workflow/configset-{configSetId}/partner_site/{steps}
I am currently using following code to generate a URL. But in this way I have to redefine the confgSetId, so, is there any other way to replace only "steps" (emailtemplates with contactpoints) route pattern?
$routes = new RouteCollection();
$routes->add('deploy_config', new Route('/config/workflow/configset-{configSetId}/partner_site/{steps}'));
$context = new RequestContext();
$context->fromRequest($this->getRequest());
$urlGenerator = new UrlGenerator($routes, $context);
$r = $urlGenerator->generate('deploy_config', array('configSetId' => $this->getConfigSet()->getId(), 'steps' => 'contactpoints'));
If I ask it simply I want to know:
How to edit current URL inside a controller in Symfony2?
You could redirect to the new url like this assuming you are inside an action:
return $this->redirect($r);
Here is the relating part in the documentation: http://symfony.com/doc/current/book/controller.html#redirecting
To get the current route use this:
$currentRoute = $request->attributes->get('_route');
$currentUrl = $this->get('router')->generate($currentRoute, array(), true);
Therefore you need to implement the Request in the action:
use Symfony\Component\HttpFoundation\Request;
...
function someAction(Request $request){