Silex app->redirect does not match routes - php

Let my application run on localhost, the path is: localhost/silex/web/index.php, defined routes as in the code below, I'd expect visiting localhost/silex/web/index.php/redirect redirects me to localhost/silex/web/index.php/foo and displays 'foo'. Instead it redirects me to localhost/foo.
I am new to Silex and maybe I got it all wrong. Could someone explain where is the problem? Is it correct behavior and it should redirect for absolute paths? Thanks.
<?php
require_once __DIR__.'/../vendor/autoload.php';
use Symfony\Component\HttpFoundation\Response;
$app = new Silex\Application();
$app['debug'] = true;
$app->get('/foo', function() {
return new Response('foo');
});
$app->get('/redirect', function() use ($app) {
return $app->redirect('/foo');
});
$app->run();

The redirect url expects an url to redirect to, not an in-app route. Try it this way:
$app->register(new Silex\Provider\UrlGeneratorServiceProvider());
$app->get('/foo', function() {
return new Response('foo');
})->bind("foo"); // this is the route name
$app->get('/redirect', function() use ($app) {
return $app->redirect($app["url_generator"]->generate("foo"));
});

For internal redirects, which does not change the requested URL, you can also use a sub-request:
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;
$app->get('/redirect', function() use ($app) {
$subRequest = Request::create('/foo');
return $app->handle($subRequest, HttpKernelInterface::SUB_REQUEST, false);
});
See also Making sub-Requests.

Up to "silex/silex": ">= 2.0", a native trait allow you to generate an URL based on the route name.
You can replace :
$app['url_generator']->generate('my-route-name');
By :
$app->path('my-route-name');
Then use it to redirect :
$app->redirect($app->path('my-route-name'));
Another possibility is to create a custom trait to directly redirect with a route name :
namespace Acme;
trait RedirectToRouteTrait
{
public function redirectToRoute($routeName, $parameters = [], $status = 302, $headers = [])
{
return $this->redirect($this->path($routeName, $parameters), $status, $headers);
}
}
Add the trait to your application definition :
use Silex\Application as BaseApplication;
class Application extends BaseApplication
{
use Acme\RedirectToRouteTrait;
}
Then use it wherever you need it :
$app->redirectToRoute('my-route-name');

Related

Understanding Slim 4 routing function

I am trying to learn slim framework and I am following the tutorial. What I would like is a detailed explanation of what the be low snippet of code is doing within the slim environment.
$app->get('/client/{name}'
The reason that I am asking is because in keep getting route not found. But I have yet to figure out why. The base route works. But when I added the twig and tried to route to that. It fails.
Now comes the code:
This part is in my webroot/public/index.php
<?php
use DI\Container;
use Slim\Factory\AppFactory;
use Slim\Views\Twig;
use Slim\Views\TwigMiddleware;
use Twig\Error\LoaderError;
require __DIR__ . '/../vendor/autoload.php';
$container = new Container;
$settings = require __DIR__ . '/../app/settings.php';
$settings($container);
AppFactory::setContainer($container);
$app = AppFactory::create();
$app->addRoutingMiddleware();
$app->addErrorMiddleware(true, true, true);
// Create Twig
$twigPath = __DIR__ . "/../templates";
$twig = '';
try {
$twig = Twig::create($twigPath, ['cache' => false]);
} catch (LoaderError $e) {
echo "Error " . $e->getMessage();
}
// Add Twig-View Middleware
$app->add(TwigMiddleware::create($app, $twig));
$routes = require __DIR__ . '/../app/routes.php';
$routes($app);
$app->run();
This part is in the routes.php:
<?php
use Slim\App;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Views\Twig;
return function (App $app) {
$app->get('/', function (Request $request, Response $response, array $args) {
$response->getBody()->write("Hello world! Really?");
return $response;
});
$app->get('/client/{name}', function (Request $request, Response $response, $args) {
$view = Twig::fromRequest($request);
return $view->render($response, 'client_profiles.html', [
'name' => $args['name']
]);
})->setName('profile');
};
The first route works fine the second does not. According to what I am reading. It should work. https://www.slimframework.com/docs/v4/features/templates.html
I feel that if I knew what get is looking to do. I may be able to fix it and build a proper route.
When I dig into the $app->get which connects with the RouterCollecorProxy.php. There is the $pattern variable and $callable. The callable is the anonymous function that comes after the common in the
$app->get('/client/{name}', function <- this is the callable, right?
I see the map class which takes me to the createRoute which returns the $methods, $pattern, callable and a few other things.
I think the pattern is where my problem is.

Add value to route before in slim framework

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...

Symfony Routing Component not routing url

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.

How to get retuned value from one laravel route into another route

How to get value of one route into another
Route::get('/first_url', function () {
return "Hello this is test";
});
I Tried something like this but not worked.
Route::get('/second_url', function () {
$other_view = Redirect::to('first_url');
});
I want to get returned value from first_url to variable $other_view in second_url to process and manipulate returned value.
Using Redirect is changing url. Which I dont want to use.
Any Idea ??? Or Am I trying wrong thing to do.
If you just want to return first_url, do this:
Route::get('/first_url', ['as' => 'firstRoute', function () {
return "Hello this is test";
}]);
Route::get('/second_url', function () {
return redirect()->route('firstRoute');
});
Learn more about redirects to routes here.
Update:
If you want to pass variable, you can use form or just create a link with parameters. You can try something like this {{ route('second_url', ['param' => 1]) }}
Then your second route will look like this:
Route::get('/second_url/{param}', ['uses' => 'MyController#myMethod', 'param' => 'param']);
And myMethod method in MyController:
public function myMethod($param){
echo $param;
...
I don't know why you would like to do this, but you can get the rendered contents of the route by executing a simple HTTP request to your route and reading the contents:
Route::get('/second_url', function () {
$other_view = file_get_contents(URL::to('first_url'));
return $other_view; // Outputs whatever 'first_url' renders
});
You need to send HTTP request and then process the response. You can use file_get_contents as #tommy has suggested or you can use HTTP library like Guzzle:
$client = new GuzzleHttp\Client();
$res = $client->get(route('firstRoute'));
in this case u should use a named route.
https://laravel.com/docs/5.1/routing#named-routes
somthing like this:
Route::get('/first_url', ['as' => 'nameOfRoute', function () {
return "Hello this is test";
}]);
Route::get('/second_url', function () {
redirect()->route('nameOfRoute');
});
You can not pass the variable value to another route directly. http is stateless protocol. if you want to preserve the value of variable to another route you can do that by 3 methods query string, sessions and cookies only. Your can pass parameter to to specific route like this
Route::get('/second_url/{param}', ['uses' => 'MyController#myMethod',
'param' => 'param']);
The idea behind achieving what you want is naming the function of your first route and calling it within both the first route and your second route. Your function will simply return the view to the first route, and retrieve the rendered html for your second.
function MyFirstRouteFunction() {
// Do whatever your do in your first route
// I assume your function return here an instance of Laravel's View
}
Route::get('/first_url', MyFirstRouteFunction);
Route::get('/second_url', function () {
$contentsOfFirstRoute = MyFirstRouteFunction()->render();
// Make use of rendered HTML
});
There is no need to make one extra HTTP request.
You should use Guzzle or curl to achive this:
Route::get('/second_url', function () {
//:::::Guzzle example:::::
$client = new GuzzleHttp\Client();
$res = $client->request('GET', 'http://...second_url...', []);
//:::::curl example:::::
$ch = curl_init();
//define options
$optArray = array(
CURLOPT_URL => 'http://...second_url...',
CURLOPT_RETURNTRANSFER => true
);
//apply those options
curl_setopt_array($ch, $optArray);
//execute request and get response
$res = curl_exec($ch);
});
Note that using Guzzle may need you to install required libraries.
If you put your first_route closure into a controller action you could try to instantiate that controller and call the method directly.
This is considered as bad practice.
routes.php
Route::get('/first_url', 'TestController#getFirstUrl');
App/Http/Controllers/TestController.php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
class TestController extends Controller
{
public function getFirstUrl()
{
return view('my-view');
}
}
routes.php
Route::get('/second_url', function () {
$controller = new \App\Http\Controllers\TestController();
$contentsOfFirstRoute = $controller->getFirstRoute();
// Make use of rendered HTML
});

How do I use slim framework route get all .. but not include except string

How do I use slim framework route get all .. but not include except string get /login
$app->get('/.*?', function () use ($uri, $app) {
$app->redirect($uri['public'].'/login');
});
$app->get('/login', function () use ($uri, $app) {
echo 'login view';
});
...
$app->post('/login', function () use ($uri, $app) {
$user_controller = new controller\user_controller();
$user_controller_login = $user_controller->login($uri, $app);
});
Slim routes are processed in order, so if you define the /login route before the catch-all, it will work in that order:
$app->get('/login', function() use($app) { ... });
$app->post('/login', ...);
$app->get('/.*', function() use($app) { $app->redirect('/login'); });
Although, I don't usually see 'catch all' style routes. Usually, you'd use URL rewriting to pass to static files not served by routes, and if you're doing this to ensure the user has logged-in to each page, you are better off using Slim Middleware to handle that.
For instance, if you had an authenticate piece of middleware, it could check on each of your routes for a login session/cookie/whatever, and if not found redirect to the login page (also passing the current url so they could be redirected back after login).
$authenticate = function() {
$app = \Slim\Slim::getInstance();
return function() use($app) {
// check for auth here somehow
if (!isset($_SESSION['user'])) {
$app->redirect('/login');
}
};
}
// Use middleware on your defined routes
$app->get('/stuff', $authenticate, function() use($app) { ... });
...

Categories