PHP - Help Developing A Basic Url Routing For Mvc
Hi guys, I am developing an MVC application and need some advice about how to set up url routing. Currently I can map a uri to modules/controllers and actions. I though I might leave the routing to last but it seems like that might have been a bad idea. Initially I though I might implement a Zend style routing approach and I still want to do this, but I am lost for thoughs on how I might go about this, I have looked at the zend router classes and understand the principle but cant seem to implement it in my own mvc.
So far I have this, $router is an instance of a router class. mapRoute takes a route name and a route object as parameters. The name will be used for convinience. The second parameter takes a route instance which currently takes two parameters, where param1 is a route pattern and param2 is deafult values for when a uri macthes the route pattern. So if a user types http://example/user/23, the router should map to user controller, profile action. The id, which is 23, will need to be injected into a request object. Finally the router object will be added to a front controller instance, so the front controller object can gain access to all the routes. Code: [Select] $router->mapRoute("user", new Route( "user/<id>", array( "controller"=>"user", "action"=>"profile" ) ) ); If any one has any ideas please do share, im not after code, unless you want to supply some, I just need some advice to stream line the whole process or what the best way might be. Any help will be greatly appreciated. Similar TutorialsHi I relatively new to MVC and trying to understand it all by coding my own MVC framework. I already have coded my (own variant) MVC application: a router calling controllers each creating CRUD(L)* forms (views) onto separate db tables. Now I want to create a dashboard with multiple forms each modifying a separate database table. I already have the ability for one controller to call another controller ad infinitum. However when I press "modify" on one of the forms I do not know how to route (call the router) to rebuild the dashboard restoring all the other forms (ie other controllers) to the same state they were in when my target form requested a modification. Basically I don't know how to go about routing in a hierarchical or nested MVC framework. Should I design a complex (non-linear tree-like) URL request that captures the state of my dashboard and have a very complex router that can decode it? Should each action be idempotent or should I use state in the session to make the request URL easier? *CRUD(L) a view with different forms for CRUD and L(ist) operations each invling different controller methods. I have tried searching under "HMVC" (but that seems to mean "modules") and "nested MVC" but for both terms I mostly get referred to established frameworks. Cheers GAJ Okay, so now I need help evolving my Log-In system... Up until now, the only place a user could log-in was on a given Article page if they wanted to add a comment to the Article. To accommodate that feature, I was setting the "Return To Page" only in my "article.php" script like this... Code: [Select] $_SESSION['returnToPage'] = $_SERVER['SCRIPT_NAME'] . '?title=' . $articleTitle; However, now I want to expand things. I'm growing increasingly confused about how to manage where to route people when they long-in?! 1.) Sometimes a user will Log-In and want to return where they were at (e.g. index.php, article1234.php) 2.) Sometimes a user might want to continue down a path (e.g. Checking Out, Registering for a Workshop, Sending a Message) Is there some kind of strategy to handle this? (nothing over complex, but there must be some Best Practices that work?! Debbie Hey all, I'm using cakephp and it asks me a question and I'm not sure what to put in, because I don't necessarily know the consequences of what I put in: Code: [Select] Would you like to create the methods for admin routing? (y/n) [y] > y You need to enable Configu :write('Routing.admin','admin') in /app/config/core.php to use admin routing. What would you like the admin route to be? Example: www.example.com/admin/controller What would you like the admin route to be? [admin] > Thanks for response Creating a basic MVC framework. I may confuse myself while asking this, so bare with me if this is confusing for you also... As far as i understand, the URLs are in the following format: www.example.com/controller/method/args My goal here is to not show 'method' in the URL if it's not necessary. For example, www.example.com/contact instead of www.example.com/contact/view. This is OK. I can accomplish this. But problems arise when I want to pass arguments in the URL. Say I have the URL: www.example.com/users <----- this would by default, user the controller 'users' and call default method, 'view'..just list all users. But say i want to view a user.. John. www.example.com/users/john How can I make my script know that 'john' is an argument, and not a method? The only way I can think of this is if I always have a method in the url .. like www.example.com/users/view/username/john As of now, my script breaks up the URL at / and the first element in the array is is the controller. It calls the controller with the other arguments. so www.example.com/users/john. The script would do (simplified) $controller = 'users' $controller = new $controller('john') the 'Users' class would then see if 'john' is a method. If it is, call it, if not, then call the default method (view) with john as argument... but what if I have a method called 'edit' and someone's username is edit? then www.example.com/users/edit would be a problem. So my guestion to you guy is... how do you deal with this issue? If you have www.example.com/users/edit, how do you let the script know that 'edit' is someone's username and now a method to call? Do you pass the method in the url like so www.example.com/users/edit/edit ? Or if you have worked with a framework (Zend, cakePHP, Symfony, CodeIgniter, etc), how does the framework handle it? Ideally, i would like to be able to have www.example.com/users/john instead of www.example.com/users/view/id/john im tying to design and make a routing system for my mvc framework but im wondering the best way to do this if anyone could help on how the design pattern would be. im thinking i would have a route config file which would contain all the routes for each file routes.config <?php $routes = array('news' => 'news/index'); ?> then the routing class which would get the correct route depeding on the request class and get the dispatch class to load the controller and action? if anyone could help on the best way to do this that would be great...thanks In a project that I'm working on I can specify routing rules, which is somewhat similar to mod_rewrite but in PHP. It's currently set up to use full regular expressions, but it's kind of overkill. I'm trying to convert it to use routing rules similar to some of the php frameworks I've seen. The code I've written up below is working, and while it's unlikely that I would need anything more complex, I'm wondering if anyone would like to comment, offer suggestions, or offer criticisms. This little piece of code is just a part of a bigger routing class, but this is the code that I'm concerned with. Thanks.
<?php $cfg['routes'] = [ 'cars/(:any)/(:any)/(:num).php' => 'cars/$3/$1/$2', 'default_route' => 'cars/index', 'trucks/parts?year=(:num)' => 'parts/trucks/$1', 'vans/articles(:any)' => 'articles$1' ]; $uris = [ 'cars/toyota/tercel/2014.php', # /cars/2014/toyota/tercel 'default_route', # /cars/index 'trucks/parts?year=2014', # /parts/trucks/2014 'vans/articles?p=42342' # /articles?p=42342 ]; $i = 0; foreach( $cfg['routes'] as $k => $v ) { $k = '|^' . preg_quote( $k ) . '$|uiD'; $k = str_replace( [ '\(\:any\)', '\(\:alnum\)', '\(\:num\)', '\(\:alpha\)', '\(\:segment\)' ], [ '(.+)', '([[:alnum:]]+)', '([[:digit:]]+)', '([[:alpha:]]+)', '([^/]*)' ], $k ); echo '<br />' . $uris[$i] . '<br />' . $k . '<br />'; if( @preg_match( $k, $uris[$i] ) ) { echo preg_replace( $k, $v, $uris[$i] ) . '<br /><br />'; } $i++; } This topic has been moved to Application Design. http://www.phpfreaks.com/forums/index.php?topic=332538.0 Hi all, I am looking for scripts/tutorials to create a range of simple graphical displays like bar graphs and pie charts. Does anyone know of some good tutorials to get me started? Thanks This is the view of the events (basic) Can I do the if/else statement to chose font color base of a MySQL Query Result? (see below) And No matter how I have written this, it will not turn into a scrolling table. I want the headers to stay fixed. I also don't want to rely on Java-most of the staff logs in mobile. I will if I have to though! The other thing I am not seeing how to do, but I know is also possible.... having an "edit event" "view positions" buttons. I am thinking it has to do with storing a variable, but how do you make sure the variables code pulls the event singularly from your query using the Event_ID ?? This is my first site outside of an HTML site. This is the raw synopsis: Building a site that has users with profiles & 6 permission levels. Client & various staffing levels; I use php to code the access because it is not so much about being able to query/change the database-its more so I am handling with php. There is a time log, and keeps up with the pay to the staff and what the client owes per their hours. This is the first layer view once logged in as any staffmember (sans the edit event which is reserved for high perm staff) upon clicking "view positions" they need to be able to request the shift (separate table-please correct me if I am wrong-I have all foreign keys in database in place so making this event table should be along the same as all the others but with diff variables/queries etc. So in theory all I have to do is get the grabbing of the ID field and using it down) Here is my code. Why is it not setting the client named in green? <html> <body> <?php require_once('auth.php'); ?> <?php $sql = "SELECT * FROM Events ORDER BY EventDate DESC LIMIT 40"; $sqlRes = mysql_query($sql); $req1 = mysql_num_rows($sqlRes); $colorpick = $sqlRes['BusinessName'];?> <div class="event_view"> <table border="1" cellspacing="2" cellpadding="2" width="100%" height="100%" bgcolor="silver" style="border-collapse:collapse;"> <tr> <th><font face="Arial, Helvetica, sans-serif" color="black">Event Date</font></th> <th><font face="Arial, Helvetica, sans-serif" color="black">Event Name</font></th> <th><font face="Arial, Helvetica, sans-serif" color="black">Start Time</font></th> <th><font face="Arial, Helvetica, sans-serif" color="black">End Time</font></th> <th><font face="Arial, Helvetica, sans-serif" color="black">Client Name</font></th> </tr> <?php $i=0; while ($i < $req1) { $f1=mysql_result($sqlRes,$i,"EventDate"); $f2=mysql_result($sqlRes,$i,"EventName"); $f3=mysql_result($sqlRes,$i,"Hour"); $f4=mysql_result($sqlRes,$i,"EndHour"); $f5=mysql_result($sqlRes,$i,"BusinessName"); ?> <tr> <td><font face="Arial, Helvetica, sans-serif" color="black"><?php echo $f1; ?></font></td> <td><font face="Arial, Helvetica, sans-serif" color="black"><?php echo $f2; ?></font></td> <td><font face="Arial, Helvetica, sans-serif" color="black"><?php echo $f3; ?></font></td> <td><font face="Arial, Helvetica, sans-serif" color="black"><?php echo $f4; ?></font></td> <td><?php if($colorpick == 'ClientA') { ?> <font face="Arial, Helvetica, sans-serif" color="green"><?php echo $f5; ?></font>; <?php } else($colorpick != 'ClientA'); ?> <font face="Arial, Helvetica, sans-serif" color="black"><?php echo $f5; ?></font></td> </tr> <?php $i++; } ?> </table> </div> </body> </html> I would like to develop a classifieds website like olx.in. For that choosing a PHP as language is good or not? Please let me know your suggestions for starting the development. HI everyone, Here is my code: Code: [Select] $myFile = "newuser.txt"; $fh = fopen($myFile, 'r'); $theData = fread($fh, 55); fclose($fh); $pices=explode(' ', $theData); And it opens up newuser.txt which is: "I love girls LOL 77" The "I Love GIRLS LOL" is the username of the user and the 77 is the id of the user! But when I echo it out like this: Code: [Select] <a href=".?act=Profile&id='.$pices[1].'">'.$pices[0].'</a> It shows only the letter "i"? How do I make it show the full username even if it has spaces? Hi Everyone !!!! Hi guys, PHP Noobie here. Sorry if I am not using the correct terminology. I am editing a site that was developed in php and all their page.php files are in one folder, the public_html folder. I downloaded the site locally and am using EasyPHP to view changes to the site. My initial problem is, when developing locally, only some of the links work. The following link works. <a class="red" href="benefits.php">Click here</a> The following link does not work. Error 404 <a class="red" href="/placement/">Click here</a> Also, the links in the flash banner do not work... They request this url: http://127.0.0.1:8888/services.php If I type in: http://127.0.0.1:8888/MyCompany/services.php , the browser will then render the page. Finally the scripts cant connect to the database and any user requesting information does not have access. Warning: mysql_query() [function.mysql-query]: Access denied for user ''@'localhost' (using password: NO) in C:\Program Files (x86)\EasyPHP-5.3.6.0\www\MyCompany\placement\index.php on line 108 Warning: mysql_query() [function.mysql-query]: A link to the server could not be established in C:\Program Files (x86)\EasyPHP-5.3.6.0\www\MyCompany\placement\index.php on line 108 Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\Program Files (x86)\EasyPHP-5.3.6.0\www\MyCompany\placement\index.php on line 109 Any Ideas on this problem or and foresight on other problems I may run into... with the database maybe? I am working on a project where I want a select form to display information from a MySQL table. The select values will be different sports (basketball,baseball,hockey,football) and the display will be various players from those sports. I have set up so far two tables in MySQL. One is called 'sports' and contains two columns. Once called 'category_id' and that is the primary key and auto increments. The other column is 'sports' and contains the various sports I mentioned. For my select menu I created the following code. <?php #connect to MySQL $conn = @mysql_connect( "localhost","uname","pw") or die( "You did not successfully connect to the DB!" ); #select the specified database $rs = @mysql_SELECT_DB ("test", $conn ) or die ( "Error connecting to the database test!"); ?> <html> <head>Display MySQL</head> <body> <form name="form2" id="form2"action="" > <select name="categoryID"> <?php $sql = "SELECT category_id, sport FROM sports ". "ORDER BY sport"; $rs = mysql_query($sql); while($row = mysql_fetch_array($rs)) { echo "<option value=\"".$row['category_id']."\">".$row['sport']."</option>\n "; } ?> </select> </form> </body> </html> this works great. I also created another table called 'players' which contains the fields 'player_id' which is the primary key and auto increments, category_id' which is the foreign key for the sports table, sport, first_name, last_name. The code I am using the query and display the desired result is as follows <html> <head> <title>Get MySQL Data</title> </head> <body> <?php #connect to MySQL $conn = @mysql_connect( "localhost","uname","pw") or die( "Err:Db" ); #select the specified database $rs = @mysql_SELECT_DB ("test", $conn ) or die ( "Err:Db"); #create the query $sql ="SELECT * FROM sports INNER JOIN players ON sports.category_id = players.category_id WHERE players.sport = 'Basketball'"; #execute the query $rs = mysql_query($sql,$conn); #write the data while( $row = mysql_fetch_array( $rs) ) { echo ("<table border='1'><tr><td>"); echo ("Caetegory ID: " . $row["category_id"] ); echo ("</td>"); echo ("<td>"); echo ( "Sport: " .$row["sport"]); echo ("</td>"); echo ("<td>"); echo ( "first_name: " .$row["first_name"]); echo ("</td>"); echo ("<td>"); echo ( "last_name: " .$row["last_name"]); echo ("</td>"); echo ("</tr></table>"); } ?> </body> </html> this also works fine. All I need to do is tie the two together so that when a particular sport is selected, the query will display below in a table. I know I need to change my WHERE clause to a variable. This is what I need help with. thanks Routing issue: Cannot see a wireless router from a wired router on the same network. I have a very simple home network with a broadband connection from my ISP coming into the house with their 4-port modem/router (192.168.1.1) on it. From there I have 2 ethernet connections, one each to a wired router(192.168.1.7) and a wireless router(192.168.1.2) The wired router has one connection to my Debian Squeeze PC (usually 192.168.1.24) the wireless router has 2 or 3 connections to a PC and a tablet (usually something like 192.168.1.100 & 101... etc) The internet from my PC (192.168.1.24) is working fine through the wiired router, and the PC & tablet on the wireless router are working fine too. My problem is that I want to be able to 'see' the wireless router from my PC and I cannot connect to it or 'see' any of the connected devices. Maybe I am misunderstanding how this networking thing should work, but I think it should be possible to do this. Can anyone help me please? a) I have turned off iptables # iptables -F # iptables -L Chain INPUT (policy ACCEPT) target prot opt source destination Chain FORWARD (policy DROP) target prot opt source destination Chain OUTPUT (policy ACCEPT) target prot opt source destination Chain logdrop (0 references) target prot opt source destination b) ifconfig -a eth1 Link encap:Ethernet HWaddr fc:75:16:e1:b8:13 inet addr:192.168.1.24 Bcast:192.168.1.255 Mask:255.255.255.0 inet6 addr: fe80::fe75:16ff:fee1:b813/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:9123 errors:0 dropped:0 overruns:0 frame:0 TX packets:9696 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:1100294 (1.0 MiB) TX bytes:844749 (824.9 KiB) Interrupt:20 Base address:0xde00 lo Link encap:Local Loopback inet addr:127.0.0.1 Mask:255.0.0.0 inet6 addr: ::1/128 Scope:Host UP LOOPBACK RUNNING MTU:16436 Metric:1 RX packets:2740 errors:0 dropped:0 overruns:0 frame:0 TX packets:2740 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:247076 (241.2 KiB) TX bytes:247076 (241.2 KiB) b) I have added routes(I think) to the other router from my PC # route -n Kernel IP routing table Destination Gateway Genmask Flags Metric Ref Use Iface 192.168.1.1 192.168.1.7 255.255.255.255 UGH 0 0 0 eth1 192.168.1.2 192.168.1.1 255.255.255.255 UGH 0 0 0 eth1 192.168.1.0 0.0.0.0 255.255.255.0 U 0 0 0 eth1 0.0.0.0 192.168.1.7 0.0.0.0 UG 0 0 0 eth1 # arp -an ? (192.168.1.7) at 00:14:6c:0b:1d:da [ether] on eth1 ========================================== from the other end, the wireless router when I connect a wired connection to a laptop I get the following similar picture (the broadband router) # ping 192.168.1.1 PING 192.168.1.1 (192.168.1.1) 56(84) bytes of data. From 192.168.1.107 icmp_seq=2 Destination Host Unreachable From 192.168.1.107 icmp_seq=3 Destination Host Unreachable From 192.168.1.107 icmp_seq=4 Destination Host Unreachable ^C --- 192.168.1.1 ping statistics --- 6 packets transmitted, 0 received, +3 errors, 100% packet loss, time 5009ms pipe 3 (the wireless router) # ping 192.168.1.2 PING 192.168.1.2 (192.168.1.2) 56(84) bytes of data. 64 bytes from 192.168.1.2: icmp_req=1 ttl=64 time=0.378 ms 64 bytes from 192.168.1.2: icmp_req=2 ttl=64 time=0.381 ms 64 bytes from 192.168.1.2: icmp_req=3 ttl=64 time=0.452 ms ^C --- 192.168.1.2 ping statistics --- 3 packets transmitted, 3 received, 0% packet loss, time 1998ms rtt min/avg/max/mdev = 0.378/0.403/0.452/0.041 ms # arp -an ? (192.168.1.1) at <incomplete> on eth0 ? (192.168.1.2) at b0:48:7a:67:ea:7a [ether] on eth0 # route -n Kernel IP routing table Destination Gateway Genmask Flags Metric Ref Use Iface 192.168.1.0 0.0.0.0 255.255.255.0 U 0 0 0 eth0 169.254.0.0 0.0.0.0 255.255.0.0 U 1000 0 0 eth0 0.0.0.0 192.168.1.2 0.0.0.0 UG 0 0 0 eth0 # ifconfig eth0 Link encap:Ethernet HWaddr 00:16:d3:bb:64:09 inet addr:192.168.1.107 Bcast:192.168.1.255 Mask:255.255.255.0 inet6 addr: fe80::216:d3ff:febb:6409/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:5858 errors:0 dropped:0 overruns:0 frame:0 TX packets:5491 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:7093094 (6.7 MiB) TX bytes:666534 (650.9 KiB) Interrupt:17 lo Link encap:Local Loopback inet addr:127.0.0.1 Mask:255.0.0.0 inet6 addr: ::1/128 Scope:Host UP LOOPBACK RUNNING MTU:16436 Metric:1 RX packets:121 errors:0 dropped:0 overruns:0 frame:0 TX packets:121 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:10032 (9.7 KiB) TX bytes:10032 (9.7 KiB) Edited by Zane, 28 December 2014 - 01:06 AM. I have 3 tables (sectors, subsectors, and business). From the site a site user can select a sector, which then lists the subsectors, then when they select a sub sector they can view a list of the businesses within the selection. I am trying to remove a step so that they will see the sectors and be able to select, then will list the subsectors with the business names under the subsectors. The code I have is prior to removing the step is ...... Code: [Select] <?php $rs=mysql_query("select * from tblmain WHERE id='$view'"); while($row=mysql_fetch_row($rs)){ foreach ($row as $k => $v){ $row[$k] = nl2br($v); } echo("<h4>" . $row[1] . " Sectors </h4>"); } ?> <ul> <?php $pnds=1; if (isset($_GET["id"])) $pnds=$_GET["id"]; $sql = "select * from tblsub WHERE catid='$view' ORDER BY subsec "; $reccount=$sq->numsrow($sql); if ($reccount > 0) { $ata =$sq->query($sql); while($rs=$sq->fetch($ata)) { ?> <li><a href="listings.php?view=<?php echo $rs["subsec"];?>"><?php echo $rs["subsec"];?></a></li> <?php } } ?> </ul> I have tried to get this to work but the problem I am having is $view is an number but the actual business table is not id, it is by subsector name. I have tried ....... Code: [Select] <?php $rs=mysql_query("select * from tblmain WHERE id='$view'"); while($row=mysql_fetch_row($rs)){ foreach ($row as $k => $v){ $row[$k] = nl2br($v); } echo("<h4>" . $row[1] . " Sectors </h4>"); } ?> <ul> <?php $pnds=1; if (isset($_GET["id"])) $pnds=$_GET["id"]; $sql = "select * from tblsub WHERE catid='$view' ORDER BY subsec "; $reccount=$sq->numsrow($sql); if ($reccount > 0) { $ata =$sq->query($sql); while($rs=$sq->fetch($ata)) { ?> <li><a href="listings.php?view=<?php echo $rs["subsec"];?>"><?php echo $rs["subsec"];?></a></li> <?php $rs=mysql_query("select * from tblbusiness WHERE category='$view' ORDER BY name"); while($row=mysql_fetch_row($rs)){ foreach ($row as $k => $v){ $row[$k] = nl2br($v); } print(" . $row[2] . "); } <?php } } ?> </ul> But obviously category is by name and not $view which is an id. Any help would be greatly appreciated. I'm trying to create a website so that if I go to http://websiteaddress.com/, it will go to then index and if you are already logged in it will display the main page, but if you aren't logged in it'll show a login/registration page. Also, how does the following work: index.php?action=home index.php?action=register They show two seperate pages? So, could it go to the home page if logged in, but if not logged in it'll go the registration/login page? Hello, Im from the Netherlands and i have a little question about php. I have a form in php where administrators can make new users. They can fill in a name, password, age and can select a role. The role is a dropdown menu where they can select athlete, researcher and trainer. My problem is that when they select a role, i want that selected role transfert to a php variable. I want to use the variable in a if statment, when sporter selected a new dropdown appears with options like tennis, hockey.... I have seen a lot on google about this with jquery and stuff, but i cant find a good example. Can u help me? Thanks. |