Replace matches from one string in another string - php

I'm writing a router for my PHP MVC application, and I currently need to find a way to use matches in a route as variables for controllers and actions.
For example, if I have the following route: /users/qub1/home
I would like to use a regex similar to this: \/users\/(?!/).*\/(?!/).*
Then I would like to specify the action like this: $2 (in the example, this would be home)
And the parameter to pass to the action like this: $1 (in the example, this would be qub1).
This would then execute code similar to this:
$controller = new UsersController();
$controller->$2($1);
Configured routes are stored as such:
public function setRoute($route, $regex = false, $controller = 'Index', $action = 'index', $parameters = array()) {
if(!$regex) {
$route = preg_quote($route, '/');
}
$this->routes[] = [
'route' => $route,
'controller' => $controller,
'action' => $action,
'parameters' => $parameters
];
}
Where the above example would be stored like this: $router->setRoute('\/users\/(?!/).*\/(?!/).*', true, 'User', '$2', [$1]);
So essentially, I want to use matched groups from one regex expression as variables to replace inside another regex expression (if that makes sense).
I hope I've described my problem accurately enough. Thanks for the help.
EDIT:
The code I'm currently using to parse routes (it doesn't work, but it should illustrate what I'm trying to achieve):
public function executeRoute($route) {
// Loop over available routes
foreach($this->routes as $currentRoute) {
// Check if the current route matches the provided route
if(preg_match('/^' . $currentRoute['route'] . '$/', '/' . $route, $matches)) {
// If it matches, perform the current route's action
// Define names
$controllerClass = preg_replace('\$.*\d', $matches[str_replace('$', '', '$1')], ucfirst($currentRoute['controller'] . 'Controller'));
$actionMethod = preg_replace('\$.*\d', $matches[str_replace('$', '', '$1')], strtolower($currentRoute['action']) . 'Action');
$parameters = preg_replace('\$.*\d', $matches[str_replace('$', '', '$1')], join(', ', $currentRoute['parameters']));
// Create the controller
$controller = new $controllerClass();
$controller->$actionMethod($parameters);
// Return
return;
}
}
}

While I am not sure that it is a very well designed approach, it is doable. This is the code that replaces yours within the if:
// you already specify the controller name, so no need for replacing
$controllerClass = ucfirst($currentRoute['controller'] . 'Controller');
// also here, no need to replace. You just need to get the right element from the array
$actionMethod = strtolower($matches[ltrim($currentRoute['action'], '$')] . 'Action';
// here I make the assumption that this parameter is an array. You might want to add a check here
$parameters = array();
foreach ($currentRoute['parameters'] as $parameter) {
$parameters[] = $matches[ltrim($parameter, '$')];
}
// check before instantiating
if (!class_exists($controllerClass)) {
die('invalid controller');
}
$controller = new $controllerClass();
// also check before invoking the method
if (!method_exists($controller, $actionMethod)) {
die('invalid method');
}
// this PHP function allows to call the function with a variable number of parameters
call_user_func_array(array($controller, $actionMethod), $parameters);
One reason why your approach is not very favorable is that you make a lot of assumptions:
the regex needs to have as many groups as you use in the other parameters
if you are imprecise with the regex, it might be possible to call any method in your code
Maybe this will be good enough for your project but you should consider using a well-established router if you want to create something not for educational purposes.

Related

Simple PHP Routing Project

I need to create a simple routing mechanism that takes a request like: /foo/bar and translates it to FooController->barAction(); I have to use a single script as an access point to load these controller classes and action methods. I also cannot use any external frameworks or libraries to accomplish this task. This needs to be able to be run on a PHP 5.3 Server with Apache.
Below is what I've written already, but I'm having trouble getting it to work:
class Router {
private static $routes = array();
private function __construct() {}
private function __clone() {}
public static function route($pattern, $callback) {
$pattern = '/' . str_replace('/', '\/', $pattern) . '/';
self::$routes[$pattern] = $callback;
}
public static function execute() {
$url = $_SERVER['REQUEST_URI'];
$base = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME']));
if (strpos($url, $base) === 0) {
$url = substr($url, strlen($base));
}
foreach (self::$routes as $pattern => $callback) {
if (preg_match($pattern, $url, $params)) {
array_shift($params);
return call_user_func_array($callback, array_values($params));
}
}
}
}
I'm trying to at least execute my current script which is based off another simple Router, but I cannot actually get an output using
Router::route('blog/(\w+)/(\d+)', function($category, $id){
print $category . ':' . $id;
});
Router::execute();
Instead of trying to break out the PATH. Why not use .htaccess instead.
So you could have internal URL's that look like this:
index.php?module=MODULE&action=INDEX
Then use .htaccess to provide the paths in the URL and the route them accordingly.
www.mydomain.com/MODULE/INDEX
This post can help with the rewriting regex for creating pritty urls in htaccess
There might be a better one, was just a quick google search.
This way you can access like this:
$module = $_GET['module'];
$action = $_GET['action];
Then you can do checks to corresponding actions in your router to check if it exists and then re-route accordingly.

Yii Overwrite createUrl but keep parameters

I am extending and overwriting the createUrl method to make pretty URLs.
Here is a snippet:
public function createUrl($manager, $route, $params, $ampersand) {
if($route == 'widget/view'){
$widget = Widget::model()->findByPk($params['id']);
return 'widget/' . $params['id'] . '/' . SEOUrlRule::slug($widget->title);
}
}
Lots of things don't matter much here. And I removed irrelevant parts.
It works fine. However, sometimes the method may be called with additional parameters such as an anchor tag, or GET parameters to put at the end of the URL.
Using my method, these parameters will be lost. To pass them forward in the new URL, do I have to re-do whatever the original createUrl method did manually? Or is there a nice object oriented way to pass the job along to a competent method?
You've made every argument required - is that intentional?
You can have Yii construct the parameter string by using the createUrl from CApplication, e.g.:
public function createUrl($manager, $route, $params, $ampersand) {
if($route == 'widget/view'){
$widget = Widget::model()->findByPk($params['id']);
$url = 'widget/' . $params['id'] . '/' . SEOUrlRule::slug($widget->title);
return Yii::app()->createUrl(trim($url,'/'),$params,$ampersand);
}
}

Creating canonical URLs with custom route-classes

I'm trying to implement canonical URLs and combine it with custom route-classes.
The URL-scheme is something like this:
/category-x/article/123
/category-y/article/123
I create a custom route-class extending Zend_Controller_Router_Route_Regex and checks that the article 123 exists and that the URL includes the correct category-name. If article 123 belongs in category-x and the user is accessing category-y I want to redirect to the correct URL.
But the routes does not have any obvious possibility to do this directly. What's the best practice approach here?
I often do this in my action controller. Something like this...
// assuming GET /category-y/article/123
// $article->url is generated, and contains /category-x/article/123
if (this->_request->getRequestUri() != $article->url) {
return $this->_helper->redirector->goToUrl($article->url);
}
In this example, $article->url would need to be generated from your database data. I often use this to verify a correct slug, when I also pull in the object id.
You could also potentially move this to your routing class, if you wanted to use a custom one instead of using Regex (you could subclass it).
I ended up with this solution:
The custom route-class creates the canonical URL in its match()-method like this:
public function match($path, $partial = false) {
$match = parent::match($path, $partial);
if (!empty($match)) {
$article = $this->backend->getArticle($match['articleId']);
if (!$article) {
throw new Zend_Controller_Router_Exception('Article does not exist', 404);
}
$match['canonicalUrl'] = $this->assemble(array(
'title' => $article->getTitle(),
'articleId' => $article->getId()
));
}
return $match;
}
$article is populated inside match() if the parent::match() returns array.
I've created a front controller plugin which hooks on the routeShutdown() like this:
public function routeShutdown(Zend_Controller_Request_Abstract $request) {
if ($request->has('canonicalUrl')){
$canonicalUrl = $request->getBaseUrl() . '/' . $request->get('canonicalUrl');
if ($canonicalUrl != $request->getRequestUri()) {
$this->getResponse()->setRedirect($canonicalUrl, 301);
}
}
}
It simply checks if the route(custom or native Zend) created a canonical URL and if the requested URL does not match, redirect to the correct canonical URL.

MVC; Arbitrary routing path levels and parameters

I'm working on an (oh no, not another) MVC framework in PHP, primarily for education, but also fun and profit.
Anyways, I'm having some trouble with my Router, specifically routing to the correct paths, with the correct parameters. Right now, I'm looking at a router that (using __autoload()) allows for arbitrarily long routing paths:
"path/to/controller/action"
"also/a/path/to/a/controller/action"
Routing starts at the application directory, and the routing path is essentially parallel with the file system path:
"/framework/application/path/to/controller.class.php" => "action()"
class Path_To_Controller{
public function action(){}
}
"/framework/application/also/a/path/to/a/controller.class.php" => "action()"
class Also_A_Path_To_A_Controller{
public function action(){}
}
This will allow for module configuration files to be available at varying levels of the application file system. The problem is of course, when we introduce routing path parameters, it becomes difficult differentiating where the routing path ends and the path parameters begin:
"path/to/controller/action/key1/param1/key2/param2"
Will obviously be looking for the file:
"/framework/application/path/to/controller/action/key1/param1/key2.class.php"
=> 'param2()'
//no class or method by this name can be found
This ain't good. Now this smells like a design issue of course, but I'm certain there must be a clean way to circumvent this problem.
My initial thoughts were to test each level of the routing path for directory/file existence.
If it hits 1+ directories followed by a file, additional path components are an action followed by parameters.
If it hits 1+ directories and no file is found, 404 it.
However, this is still susceptible to erroneously finding files. Sure this can be alleviated by stricter naming conventions and reserving certain words, but I'd like to avoid that if possible.
I don't know if this is the best approach. Has anyone solved such an issue in an elegant manner?
Well, to answer my own question with my own suggestion:
// split routePath and set base path
$routeParts = explode('/', $routePath);
$classPath = 'Flooid/Application';
do{
// append part to path and check if file exists
$classPath .= '/' . array_shift($routeParts);
if(is_file(FLOOID_PATH_BASE . '/' . $classPath . '.class.php')){
// transform to class name and check if method exists
$className = str_replace('/', '_', $classPath);
if(method_exists($className, $action = array_shift($routeParts))){
// build param key => value array
do{
$routeParams[current($routeParts)] = next($routeParts);
}while(next($routeParts));
// controller instance with params passed to __construct and break
$controller = new $className($routeParams);
break;
}
}
}while(!empty($routeParts));
// if controller exists call action else 404
if(isset($controller)){
$controller->{$action}();
}else{
throw new Flooid_System_ResponseException(404);
}
My autoloader is about as basic as it gets:
function __autoload($className){
require_once FLOOID_PATH_BASE . '/' . str_replace('_', '/', $className) . '.class.php';
}
This works, surprisingly well. I've yet to implement certain checks, like ensuring that the requested controller in fact extends from my Flooid_System_ControllerAbstract, but for the time being, this is what I'm running with.
Regardless, I feel this approach could benefit from critique, if not a full blown overhaul.
I've since revised this approach, though it ultimately performs the same functionality. Instead of instantiating the controller, it passes back the controller class name, method name, and parameter array. The guts of it all are in getVerifiedRouteData(), verifyRouteParts() and createParamArray(). I'm thinking I want to refactor or revamp this class though. I'm looking for insight on where I can optimize readability and usability.:
class Flooid_Core_Router {
protected $_routeTable = array();
public function getRouteTable() {
return !empty($this->_routeTable)
? $this->_routeTable
: null;
}
public function setRouteTable(Array $routeTable, $mergeTables = true) {
$this->_routeTable = $mergeTables
? array_merge($this->_routeTable, $routeTable)
: $routeTable;
return $this;
}
public function getRouteRule($routeFrom) {
return isset($this->_routeTable[$routeFrom])
? $this->_routeTable[$routeFrom]
: null;
}
public function setRouteRule($routeFrom, $routeTo, Array $routeParams = null) {
$this->_routeTable[$routeFrom] = is_null($routeParams)
? $routeTo
: array($routeTo, $routeParams);
return $this;
}
public function unsetRouteRule($routeFrom) {
if(isset($this->_routeTable[$routeFrom])){
unset($this->_routeTable[$routeFrom]);
}
return $this;
}
public function getResolvedRoutePath($routePath, $strict = false) {
// iterate table
foreach($this->_routeTable as $routeFrom => $routeData){
// if advanced rule
if(is_array($routeData)){
// build rule
list($routeTo, $routeParams) = each($routeData);
foreach($routeParams as $paramName => $paramRule){
$routeFrom = str_replace("{{$paramName}}", "(?<{$paramName}>{$paramRule})", $routeFrom);
}
// if !advanced rule
}else{
// set rule
$routeTo = $routeData;
}
// if path matches rule
if(preg_match("#^{$routeFrom}$#Di", $routePath, $paramMatch)){
// check for and iterate rule param matches
if(is_array($paramMatch)){
foreach($paramMatch as $paramKey => $paramValue){
$routeTo = str_replace("{{$paramName}}", $paramValue, $routeTo);
}
}
// return resolved path
return $routeTo;
}
}
// if !strict return original path
return !$strict
? $routePath
: false;
}
public function createParamArray(Array $routeParts) {
$params = array();
if(!empty($routeParts)){
// iterate indexed array, use odd elements as keys
do{
$params[current($routeParts)] = next($routeParts);
}while(next($routeParts));
}
return $params;
}
public function verifyRouteParts($className, $methodName) {
if(!is_subclass_of($className, 'Flooid_Core_Controller_Abstract')){
return false;
}
if(!method_exists($className, $methodName)){
return false;
}
return true;
}
public function getVerfiedRouteData($routePath) {
$classParts = $routeParts = explode('/', $routePath);
// iterate class parts
do{
// get parts
$classPath = 'Flooid/Application/' . implode('/', $classParts);
$className = str_replace('/', '_', $classPath);
$methodName = isset($routeParts[count($classParts)]);
// if verified parts
if(is_file(FLOOID_PATH_BASE . '/' . $classPath . '.class.php') && $this->verifyRouteParts($className, $methodName)){
// return data array on verified
return array(
'className'
=> $className,
'methodName'
=> $methodName,
'params'
=> $this->createParamArray(array_slice($routeParts, count($classParts) + 1)),
);
}
// if !verified parts, slide back class/method/params
$classParts = array_slice($classParts, 0, count($classParts) - 1);
}while(!empty($classParts));
// return false on not verified
return false;
}
}

Is there a Symfony helper for getting the current action URL and changing one or more of the query parameters?

What I'd like to do is take the route for the current action along with any and all of the route and query string parameters, and change a single query string parameter to something else. If the parameter is set in the current request, I'd like it replaced. If not, I'd like it added. Is there a helper for something like this, or do I need to write my own?
Thanks!
[edit:] Man, I was unclear on what I actually want to do. I want to generate the URL for "this page", but change one of the variables. Imagine the page I'm on is a search results page that says "no results, but try one of these", followed by a bunch of links. The links would contain all the search parameters, except the one I would change per-link.
Edit:
Ok I got a better idea now what you want. I don't know whether it is the best way but you could try this (in the view):
url_for('foo',
array_merge($sf_request->getParameterHolder()->getAll(),
array('bar' => 'barz'))
)
If you use this very often I suggest to create your own helper that works like a wrapper for url_for.
Or if you only want a subset of the request parameters, do this:
url_for('foo',
array_merge($sf_request->extractParameters(array('parameter1', 'parameter3')),
array('bar' => 'barz'))
)
(I formated the code this way for better readability)
Original Answer:
I don't know where you want to change a parameter (in the controller?), but if you have access to the current sfRequest object, this should do it:
$request->setParameter('key', 'value')
You can obtain the request object by either defining your action this way:
public function executeIndex($request) {
// ...
}
or this
public function executeIndex() {
$request = $this->getRequest();
}
For symfony 1.4 I used:
$current_uri = sfContext::getInstance()->getRouting()->getCurrentInternalUri();
$uri_params = $sf_request->getParameterHolder()->getAll();
$url = url_for($current_uri.'?'.http_build_query(array_merge($uri_params, array('page' => $page))));
echo link_to($page, $url);
Felix's suggestion is good, however, it'd require you to hard core the "current route"..
You can get the name of the current route by using:
sfRouting::getInstance()->getCurrentRouteName()
and you can plug that directly in url_for, like so:
url_for(sfRouting::getInstance()->getCurrentRouteName(),
array_merge($sf_request->extractParameters(array('parameter1', 'parameter3')),
array('bar' => 'barz'))
)
Hope that helps.
With the same concept than Erq, and thanks to his code, I have made the same with some small changes, since my URL needs to convert some characters. Its generic though and should work with most forms, in order to save the parameters the user has chosen to search for.
public function executeSaveFormQuery(sfWebRequest $request)
{
$sURLServer = "http://";
$sURLInternalUri = "";
$page = "";
$sURLInternalUri = sfContext::getInstance()->getRouting()->getCurrentInternalUri();
$suri_params = $request->getParameterHolder()->getAll();
$sParams = http_build_query(array_merge($suri_params));
$dpos = strpos($sURLInternalUri, "?");
$sURLConsulta[$dpos] = '/';
$sURL = substr($sURLInternalUri, $dpos);
$dpos = strpos($sURL, "=");
$sURL[$dpos] = '/';
$sURLFinal = $sURLServer . $sURL . '?' . $sParams;
//$this->redirect($this->module_name . '/new');
self::executeNew($request, $sURLFinal);
//echo "var_dump(sURLFinal): ";
//var_dump($sURLFinal);
//echo "<br></br>";
//return sfView::NONE;
}
In executeNew, as easy as:
public function executeNew(sfWebRequest $request, $sURLQuery)
{
//$sURLQuery= "http://";
if ($sURLQuery!= "")
{
$this->form = new sfGuardQueryForm();
//echo "var_dump(sURLQuery)";
//var_dump($sURLQuery);
//echo "<br></br>";
$this->form->setDefault('surl', $sURLQuery);
}
else
{
$this->form = new sfGuardQueryForm();
}
}
echo $sf_context->getRequest()->getUri();

Categories