send each request to appropriate controller - php

I want to make a small web application, and I'm not sure how to go about this.
What I want to do is send every request to the right controller. Kind of how CodeIgniter does it.
So if user asks for domain.com/video/details
I want my bootstrap (index?) file to send him to the "Video" controller class and call the "details" method in that class.
If the user asks for domain.com/profile/edit I want to send him to the "Profile" controller class and call the "edit" method in that class.
Can someone explain how I should do this? I have some experience using MVC frameworks, but have never "written" something with MVC myself.
Thanks!
Edit: I understand now how the url points to the right Controller, but I don't see where the object instance of the Controller is made, to call the right method?

You need to re-route your requests. Using apache, this can be done using mod_rewrite.
For example, add a .htaccess file to your public base directory and add the following:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?rt=$1 [L,QSA]
This will redirect users trying to access
/profile/edit
to
index.php?rt=profile/edit
In index.php, you can access the $_GET['rt'] to determine which controller and action has been requested.

Use mod-rewrite (.htaccess) to
rewrite the url from
www.example.com/taco to
www.example.com/index.php?taco/
in index.php, grab the first URL
parameter key, use that to route to
the correct url. As it will look
like "taco/"
You may want to add / to the front
and back if it doesn't exist. As
this will normalize the urls and
make life easier
If you want to preserve the ability
to have traditional query strings.
Inspect the URL directly and take
the query string portion. break that
on ?, which will leave you with the
routing info in key 0 and the rest
in key 1. split that on &, then
split each of those on = and set the
first to the key and the second to
the value of an array. Replace $_GET
with that array.
Example:
$path = explode("?", $_SERVER["QUERY_STRING"],2);
$url = $path[0];
if(substr($url,0,1) != "/")
{
$url = "/".$url;
}
if(substr($url,-1,1) != "/")
{
$url = $url."/";
}
unset($_GET);
foreach(explode("&", $path[1]) as $pair)
{
$get = explode("=", $pair, 2);
$_GET[$get[0]] = $get[1];
}
// Define the Query String Path
define("QS_PATH", $url);

Depending on what you want to do or how much work you want to do, another option versus writing your own MVC is to use Zend Framework. It does exactly what you're asking for and more. You still need to configure URL rewriting as mentioned in the other answers, but it quick and easy.
Even if you're not interested in Zend Framework, the following link can help you configure your rewrite rules: http://framework.zend.com/wiki/display/ZFDEV/Configuring%2BYour%2BURL%2BRewriter

Related

PHP MVC - Database routing?

Hi I'm currenly playing around with PHP MVC programming, and was wondering if anyone has made some sort of "routing" with a database?
I have a "page" table that looks like this: http://i.imgur.com/xS1OvjW.png
Currently all routes are hardcoded, and I thought it must be possible to do with a database..
But not only do I want to get the page and show it, I also need to be able to send parameters with it.
Example:
As shown in my page table, I have a "test" url. If i type http://demo.com/test/ I would get "rerouted" to use the "home" controller and "Index" method. But I also need to be able to type http://demo.com/test/id/40 and id/40 will be sent as params to the controller/method.
If this isn't a good thing to do, or if anyone got a better soloution please let me know! :)
Regards,
Frederik
This definitely depends on the server you're using, but since you're a PHP MVC noobie I'll reference apache in this example, and hope it's what you have for the sake of the examples.
First, you'll need your webserver configured to know that it has to send all traffic through your base page (usually index.php). Now that page would do some other stuff (call bootstrap, etc) but for the sake of argument we'll say that all it does right away is look at the request from the page, compare it to the DB, and complete the request if it can.
In that case, it will be helpful to have the request info from the server passed in to the index.php page. To do this, you'll want to configure apache with an .htaccess file similar to:
DirectoryIndex index.php
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ public/?path=$1 [L,QSA]
This tells it to use index.php for all requests that aren't specific files or directories, and to pass the full url path through to index.php as a $_GET var.
Next, in index.php, you'll want to check the path you were passed against DB of paths. Here's a really simple example to show:
<?php
// Obviously use your database and some string parsing here to match correctly
// I generally explode the path on '/' to break it into controller, action, etc.
if ($_GET['path'] == "user/account") {
// Then you call the controller that matches the first part of the route
// The action that matches the second part of your route
// And pass the request along so you can access anything else
call UserController::accountAction($_REQUEST);
} else if ($_GET['path'] == "user/resetpassword") {
call UserController::resetPasswordAction($_REQUEST);
}
From there, you should be in the right place and have everything you need. That Controller/Action URL format is a fairly common one for how easily it lets us do this.
Hope the answer helped!

How to check what is Written in the url bar and navigate to a certain page in php?

What i want to be able to do is if someone writes in the url bar
www.somesite.com/test
test is like the Username name so it will be www.somesite.com/Username
then page navigate to another and display data from the data where the username is the same
The page will navigate to another page and display data from he database
is this possible first of?
And this is what i have write now it not much, and i am also new to PHP
$url = 'http://'. $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$url2 = "http://www.somesite.com/"$databaseVar1=mysql_result($result,$i,"username");
if ($url) == ($url2)
{
header("location: http://somesite.com/viewcontent.php");
}
else
{
//not found
}
Am i Able to do something like this? Any help will be great-full thanks
In PHP this is not exactly possible, however, you can do the following:
www.somesite.com/index.php/test
Apache will open index.php and you can use something like $_SERVER['REQUEST_URI'] to navigate from there
You will either need to use a rewrite rule in .htaccess to redirect all requests to index.php. Index.php can then use
Or you can put a ? before the username. Then index.php will automatically get all requests. The $_SERVER['querystring'] will then receive the username.
Taken some assumptions (due to lack of complete source code in your question):
mysql connection is estabilished
proper query has been sent to mysql server
variable $i is set to meaningful value
www server is configured to rewrite requests to index.php
You only have to compare REQUEST_URI with "username" column value taken from database.
Header "Location: ..." must have capital letter "L".
And avoid usage of "==" operator when comparing strings in PHP, strcmp() function is more reliable - "==" operator tests identity not equality - it's useful to compare numeric values.
You can define the index.php as the application dispatcher and create an .htaccess file that will redirect the requests to it:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . index.php [L]
index.php:
$page = $_SERVER['REQUEST_URI']; //=> '/Users/show'
if ($page == '/some/page/') include('file_that_handles_this_request.php');
Or you could use this to create instances of classes and call methods:
$page = $_SERVER['REQUEST_URI']; //=> '/Users/show'
list($class, $method) = explode($page);
$object = new $class();
$object->{$method}();
you should use mvc architecture to get perfect as you want.
the url in mvc is like same as you want. You can call the method with the parameter from url directly. Here is a url pattern in mvc architecture -
www.yoursitename.com/controller/methodname/parameter

URL rewriting advice please

I would like to make my urls more seo friendly and for example change this:
http://www.chillisource.co.uk/product?&cat=Grocery&q=Daves%20Gourmet&page=1&prod=B0000DID5R&prodName=Daves_Insanity_Sauce
to something nice like this:
http://www.chillisource.co.uk/product/Daves_Gourmet/Daves_Insanity_Sauce
What is the best way of going about doing this? I've had a look at doing this with the htaccess file but this seems very complicated.
Thanks in advance
Ben Paton, there is in fact a very easy way out. CMSes like Wordpress tend to use it instead of messing around with regular expressions.
The .htaccess side
First of, you use an .htacess with the content below:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
Let me explain what it does (line by line):
if the apache module named mod_rewrite exists..
turn the module on
let it be known that we will rewrite anything starting after the
domain name (to only rewrite some directories, use RewriteBase
/subdir/)
if the requested path does not exist as a file...
and it doesn't even exist as a directory...
"redirect" request to the index.php file
close our module condition
The above is just a quick explanation. You don't really need it to use this.
What we did, is that we told Apache that all requests that would end up as 404s to pass them to the index.php file, where we can process the request manually.
The PHP side
On the PHP side, inside index.php, you simply have to parse the original URL. This URL is passed in the $_SERVER variable as $_SERVER['REDIRECT_URL'].
The best part, if there was no redirection, this variable is not set!
So, our code would end up like:
if ( isset( $_SERVER['REDIRECT_URL'] ) ) {
$url = explode('/', $_SERVER['REDIRECT_URL'] );
switch($url[0]){
case 'home': // eg: /home/
break;
case 'about': // eg: /about/
break;
case 'images': // eg: /images/
switch( $url[1] ){
case '2010': // eg: /images/2010/
break;
case '2011': // eg: /images/2011/
break;
}
break;
}
}
Easy Integration
I nearly forgot to mention this, but, thanks to the way it works, you can even end up not changing your existing code at all!
Less talk, more examples. Let's say your code looked like:
<?php
$page = get_page($_GET['id']);
echo '<h1>'. $page->title .'</h1>';
echo '<div>'. $page->content .'</div>';
?>
Which worked with urls like:
index.php?id=5
You can make it work with SEO URLs as well as keep it with your old system at the same time. Firstly, make sure the .htaccess contains the code I wrote in the one above.
Next, add the following code at the very start of your file:
if ( isset( $_SERVER['REDIRECT_URL'] ) ) {
$url = explode('/', $_SERVER['REDIRECT_URL'] );
$_GET['id'] = $url[0];
}
What are we doing here? Before going on two your own code, we are basically finding IDs and information from the old URL and feeding it to PHP's $_GET variable.
We are essentially fooling your code to think the request had those variables!
The only remaining hurdle to find all those pesky <a/> tags and replace their href accordingly, but that's a different story. :)
It's called a mod_rewrite, here is a tutorial:
http://www.workingwith.me.uk/articles/scripting/mod_rewrite
What about using the PATH_INFO environment variable?
$path=explode("/",getenv("PATH_INFO"));
echo($path[0]."; ".$path[1] /* ... */);
Will output
product; Daves_Gourmet; Daves_insanity_Sauce
The transition from using $_GET to using PATH_INFO environment is a good programming exercise. I think you cannot just do the task with configuration.
try some thing like this
RewriteRule ^/([a-zA-Z0-9]+)/([a-zA-Z0-9]+)/([a-zA-Z0-9]+) /$1.php?id1=$2&id2=$3 [QSA]
then use $_GET to get the parameter values...
I'll have to add: in your original url, there's a 'prod' key, which seems to consist of an ID.
Make sure that, when switching to rewritten urls, you no longer solely depend upon a unique id, because that won't be visible in the url.
Now, you can use the ID to make a distinction between 2 products with the same name, but in case of rewriting urls and no longer requiring ID in the url, you need to make sure 1 product name can not be used multiple times for different products.
Likewise, I see the 'cat'-key not being present in the desired output url, same applies as described above.
Disregarding the above-described "problems", the rewrite should roughtly look like:
RewriteRule ^/product/(.*?)/(.*?)$ /product?&cat=Grocery&q=$1&page=1&prod=B0000DID5R&prodName=$2
The q & prodName will receive the underscored value, rather than %20, so also that will require some patching.
As you can see, I didn't touch the id & category, it'll be up to you to figure out how to handle that.

Problem with redirecting and links using MVC in PHP

I try to go into MVC but come to a problem that is not explained anywhere, it is how to redirect from one to another controller.
I'm using the following .htaccess file:
RewriteEngine On
RewriteCond% {REQUEST_FILENAME}!-F
RewriteCond% {REQUEST_FILENAME}!-D
RewriteRule ^(.*)$ index.php? Url = $ 1 [L, QSA]
to use the controller directly after it put its methods and id th.
All this work accessing them in a standard way but when choosing a view to further pages ienata used directly as the controller.
<a href="next_page_controler"> NEXT_PAGE </ a>
and access the next controller, but when I want to access methods must use
<a href="next_page_controler/**controler_model**"> NEXT-pAGE_MODEL </ a>
and here we have two problems :
IN repeatedly link in address bar is displayed once again repeated as
www.site_pat/next_page_controler/next_page_controler/next_page_controler/next_page_controler/next_page_controler/controler_model
When you try to redirect as the method controler_model using header (Location: controler_name); nothing gets pulls no message or anything just want to try but the redirect does not work .
How to solve the problems I guess a lot of you have encountered these are basic things and I think that shouting at all began to work with framework should understand these basics.
Theres something wrong with your htaccess, should be something like...
RewriteEngine On
RewriteCond %{REQUEST_FILENAME}!-F
RewriteCond %{REQUEST_FILENAME}!-D
RewriteRule ^(.*)$ index.php/$1 [L, QSA]
UPDATE:
#prodigitalson coud you give me an example
So a super simple example might look like the following code. Ive never actually written a router from sractch because im typically using a framework, so there are probably soem features youll need that this doesnt include... Routing is a fairly complex things depending on how resuable you want it to be. I would reommend looking at how a few different php frameworks do it for good examples.
// define routes as a regular expression to match
$routes = array(
'default' => array(
'url' => '#^/categories/(?P<category_slug>\w*(/.*)?$#',
'controller' => 'CategoryController'
)
)
);
// request - you should probably encapsulate this in a model
$request = array();
// loop through routes and see if we have a match
foreach($routes as $route){
// on the first match we assign variables to the request and then
// stop processing the routes
if(preg_match($route['url'], $_SERVER['REQUEST_URI'], $params)){
$request['controller'] = $route['controller'];
$request['params'] = $params;
$request['uri'] = $_SERVER['REQUEST_URI'];
break;
}
}
// check that we found a match
if(!empty($request)){
// dispatch the request to the proper controller
$controllerClass = $request['controller'];
$controller = new $controllerClass();
// because we used named subpatterns int he regex above we can access parameters
// inside the CategoryController::execute() with $request['params']['category_slug']
$response = $controller->execute($request);
} else {
// send 404
}
// in this example $controller->execute() returns the compiled HTML to render, but
// but in most systems ive used it returns a View object, or the name of the template to
// to be rendered - whatever happens here this is where you send your response
print $response;
exit(0);
You shouldnt be implementing your controller routing soley from .htaccess. You should simple have all request other than for static assets go to index.php. Then on the php side you firgure out where to dispatch the request based on the pattern of the url.

How to implement URL pattern interpreter as used by Django and RoR in PHP

What's the best way to implement a URL interpreter / dispatcher, such as found in Django and RoR, in PHP?
It should be able to interpret a query string as follows:
/users/show/4 maps to
area = Users
action = show
Id = 4
/contents/list/20/10 maps to
area = Contents
action = list
Start = 20
Count = 10
/toggle/projects/10/active maps to
action = toggle
area = Projects
id = 10
field = active
Where the query string can be a specified GET / POST variable, or a string passed to the interpreter.
Edit: I'd prefer an implementation that does not use mod_rewrite.
Edit: This question is not about clean urls, but about interpreting a URL. Drupal uses mod_rewrite to redirect requests such as http://host/node/5 to http://host/?q=node/5. It then interprets the value of $_REQUEST['q']. I'm interested in the interpreting part.
If appropriate, you can use one that already exists in an MVC framework.
Check out projects such as -- in no particular order -- Zend Framework, CakePHP, Symfony, Code Ignitor, Kohana, Solar and Akelos.
have a look at the cakephp implementation as an example:
https://trac.cakephp.org/browser/trunk/cake/1.2.x.x/cake/dispatcher.php
https://trac.cakephp.org/browser/trunk/cake/1.2.x.x/cake/libs/router.php
You could also do something with mod_rewrite:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^(.*)$ $1 [L]
RewriteRule ^([a-z]{2})/(.*)$ $2?lang=$1 [QSA,L]
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
</IfModule>
This would catch urls like /en/foo /de/foo and pass them to index.php with GET parameters 'lang' amd 'url'. Something similar can be done for 'projects', 'actions' etc
Why specifically would you prefer not to use mod_rewrite? RoR uses mod_rewrite. I'm not sure how Django does this, but mod_php defaults to mapping URLs to files, so unless you create a system that writes a separate PHPfile for every possible URL (a maintenance nightmare), you'll need to use mod_rewrite for clean URLs.
What you are describing in your question should actually be the URL mapper part. For that, you could use a PEAR package called Net_URL_Mapper. For some information on how to use that class, have a look at this unit test.
The way that I do this is very simple.
I use wordpress' .htaccess file:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
What this .htaccess does is when something returns a 404, it sends the user to index.php.
In the above, /index.php is the "interpreter" for the URL.
In index.php, I have something along the lines of:
$req = $_SERVER['REQUEST_URI'];
$req = explode("/",$req);
The second line splits up the URL into sections based on "/". You can have
$area = $req['0'];
$action= $req['1'];
$id = $req['2'];
What I end up doing is:
function get_page($offset) {//offset is the chunk of URL we want to look at
$req = $_SERVER['REQUEST_URI'];
$req = explode("/",$req);
$page = $req[$offset];
return $page;
}
$area = get_page(0);
$action = get_page(1);
$id = get_page(2);
Hope this helps!
Just to second #Cheekysoft's suggestion, check out the Zend_Controller component of the Zend Framework. It is an implementation of the Front Controller pattern that can be used independently of the rest of the framework (assuming you would rather not use a complete MVC framework).
And obviously, CakePHP is the most similar to the RoR style.
I'm doing a PHP framework that does just what you are describing - taking what Django is doing, and bringing it to PHP, and here's how I'm solving this at the moment:
To get the nice and clean RESTful URLs that Django have (http://example.com/do/this/and/that/), you are unfortunately required to have mod_rewrite. But everything isn't as glum as it would seem, because you can achieve almost the same thing with a URI that contains the script's filename (http://example.com/index.php/do/this/and/that/). My mod_rewrite just forwards all calls to that format, so it's almost as usable as without the mod_rewrite trick.
To be truthful, I'm currently doing the latter method by GET (http://example.com/index.php?do/this/and/that/), and fixing stuff in case there are some genuine GET variables passed around. But my initial research says that using the direct slash after the filename should be even easier. You can dig it out with a certain $_SERVER superglobal index and doesn't require any Apache configuration. Can't remember the exact index off-hand, but you can trivially do a phpinfo() testpage to see how stuff look like under the hood.
Hope this helps.

Categories