• We just launched and are currently in beta. Join us as we build and grow the community.

Implementing Routes in PHP for MVC Frameworks Tutorial

Slenderguy55

Local Build Optimizer
S Rep
0
0
0
Rep
0
S Vouches
0
0
0
Vouches
0
Posts
152
Likes
166
Bits
2 MONTHS
2 2 MONTHS OF SERVICE
LEVEL 1 400 XP
In this tutorial, we will explore the creation of a straightforward PHP Routing System for a PHP project that utilizes an MVC (Model, View, and Controller) framework. Throughout this tutorial, I will help you grasp the concept of routing within a PHP project and provide PHP Scripts to create a basic web application with routing functionality.

But before we delve into the coding part, let's first understand the purpose of routing within the context of the MVC architectural pattern.

What is Routing in PHP MVC Framework?

In essence, Routing is a process within the script that maps the intended Controller and Action to be executed based on the requested URL. It offers the advantage of cleaner URLs and enhances the overall structure of your web application.

Implementing a Routing System in your PHP project can also result in the generation of SEO-friendly URLs. For example, consider a simple eCommerce System in PHP that includes a list.php file displaying a list of products. This file is typically associated with the Product Controller of the system's framework. Instead of using a URL like [https://samplestore.com/index.php?controller=Product&view=list]

, you can have a cleaner and more user-friendly URL like [https://samplestore.com/product/list]

Now, let's move on to the coding part of this tutorial.

As mentioned earlier, I will provide a simple web application developed in the PHP programming language that incorporates a Routing System to offer you a practical demonstration of the process.

The application that we'll create contains the following files:

- controllers
-- Index.php
-- Users.php
- .htaccess
- index.php
- routes.php

Modifying the URL Rule using .htaccess

First, we'll start by creating a .htaccess file that includes a script to modify or rewrite the URL rules for our application.

#Activate ModRewrite
RewriteEngine On

#let the folders and files to be access
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

#Rewrite URL
RewriteRule ^(.*)$ index.php?route=$1 [QSA,L]

On the script provided above, it shows that the page will be redirected directly to index.php except of the URL provided leads to a folder or files. The parameters on the URL will serve as the route.

Creating a Routing Class?

Next, let's create a PHP class for the routing system. In this example, the file is known as routes.php. The file contains the following script:

  1. <?php
  2. /**
  3. * List of routes
  4. * Data Type = Array
  5. */

  6. $routes

    =

    [
  7. [
  8. "pattern"

    =>

    '/^index$/'

    ,
  9. "method"

    =>

    "ANY"

    ,
  10. "controller"

    =>

    "Index"
  11. ]

    ,
  12. [
  13. "pattern"

    =>

    "/^user\/(\d+)$/"

    ,
  14. "method"

    =>

    "GET"

    ,
  15. "controller"

    =>

    "Users"

    ,
  16. "page"

    =>

    "edit"
  17. ]

    ,
  18. ]

    ;

  19. /**
  20. * Routing Class
  21. */
  22. class

    Routing{
  23. // route URI
  24. public

    $route

    ;
  25. // Controller
  26. public

    $controller

    ;
  27. // the object to execute from the controller
  28. public

    $page

    ;
  29. // Post, Get, and other Request Data
  30. public

    $params

    =

    [

    ]

    ;
  31. // URI parameter = the controller's object argument(s)
  32. public

    $args

    =

    [

    ]

    ;
  33. public

    function

    __construct(

    $route

    =

    ''

    )

    {
  34. if

    (

    !

    empty

    (

    $route

    )

    )

    {
  35. $this

    ->

    route

    =

    $route

    ;
  36. // Validate route
  37. if

    (

    $this

    ->

    validate_route

    (

    )

    )

    {
  38. // If route is valid
  39. ob_start

    (

    )

    ;
  40. // load the controller class
  41. include_once

    (

    "controllers/{$this->controller}

    .php"

    )

    ;

  42. if

    (

    !

    $this

    ->

    page

    )

    {
  43. // If page is not set
  44. $this

    ->

    page

    =

    'index'

    ;
  45. }
  46. // Initializing the controller with the request data
  47. $controller

    =

    new

    (

    $this

    ->

    controller

    )

    (

    $this

    ->

    params

    )

    ;
  48. // Execute the object of the class
  49. $controller

    ->

    {

    $this

    ->

    page

    }

    (

    ...

    $this

    ->

    args

    )

    ;
  50. echo

    ob_get_clean

    (

    )

    ;
  51. }

    else

    {
  52. // Throw an Error if route is not valid
  53. throw

    new

    ErrorException(

    "Undefined Route."

    )

    ;
  54. }
  55. }

    else

    {
  56. // Throw an Error if route is not defined
  57. throw

    new

    ErrorException(

    "Undefined Route."

    )

    ;
  58. }
  59. }

  60. protected

    function

    validate_route(

    )

    {
  61. global

    $routes

    ;

  62. foreach

    (

    $routes

    as

    $route

    )

    {
  63. /**
  64. * Check if the route is allowed
  65. */
  66. if

    (

    preg_match

    (

    $route

    [

    'pattern'

    ]

    ,

    $this

    ->

    route

    ,

    $matches

    )

    )

    {
  67. /**
  68. * Checking if the provided method and the request method are match
  69. */
  70. if

    (

    $route

    [

    'method'

    ]

    !=

    "ANY"

    )

    {
  71. if

    (

    $route

    [

    'method'

    ]

    !=

    $_SERVER

    [

    'REQUEST_METHOD'

    ]

    )

    {
  72. throw

    new

    ErrorException(

    "Request Method is denied!"

    )

    ;
  73. }
  74. }

  75. /**
  76. * Defining the Arguments
  77. */
  78. if

    (

    isset

    (

    $matches

    [

    1

    ]

    )

    )

    {
  79. if

    (

    !

    is_array

    (

    $matches

    [

    1

    ]

    )

    )

    {
  80. $this

    ->

    args

    =

    [

    $matches

    [

    1

    ]

    ]

    ;
  81. }

    else

    {
  82. $this

    ->

    args

    =

    $matches

    [

    1

    ]

    ;
  83. }
  84. }
  85. /**
  86. * Defining the class Object
  87. */
  88. if

    (

    isset

    (

    $route

    [

    'page'

    ]

    )

    )
  89. $this

    ->

    page

    =

    $route

    [

    'page'

    ]

    ;
  90. /**
  91. * Defining the class name
  92. */
  93. $this

    ->

    controller

    =

    $route

    [

    'controller'

    ]

    ;

  94. // Store POST Request Data
  95. $this

    ->

    params

    [

    'post'

    ]

    =

    $_POST

    ?? [

    ]

    ;
  96. // Store GET Request Data
  97. $this

    ->

    params

    [

    'get'

    ]

    =

    $_GET

    ?? [

    ]

    ;
  98. // merging matches with params
  99. $this

    ->

    params

    =

    array_merge

    (

    $this

    ->

    params

    ,

    array_filter

    (

    $matches

    )

    )

    ;
  100. return

    true

    ;
  101. }
  102. }
  103. return

    false

    ;
  104. }
  105. }
  106. ?>

The provided script file explains that the list of permitted routes in this application is defined as $routes. Each item in this array contains an array of data with the following details:

  • pattern: The URL pattern to match with the current page URL.
  • method: This will be used to check the request method.
  • controller: The controller name to execute.
  • page: The action from the controller to execute. Default: 'index'

The Routing class includes an object or function that validates the current page URL. If the current URL is found in the list of allowed routes, the controller and other essential information needed for the page will be stored for executing the route or page's intended purpose.

Creating the index file

Now, let's craft the application's index file. This vital file is responsible for loading the routes.php file, which, in turn, initiates the routing class.

  1. <?php
  2. // Load Routing Class
  3. require_once

    (

    'routes.php'

    )

    ;

  4. /**
  5. * Execute Page Routing
  6. * $_GET['route'] = Route to output
  7. */
  8. new

    Routing(

    rtrim

    (

    $_GET

    [

    'route'

    ]

    ?? ''

    ,

    '/'

    )

    )

    ;

Creating the Controllers

Finally, it's time to generate the (2) two controllers required for this application. These controllers house the actions responsible for producing sample content.

Index.php

  1. <?php

  2. class

    Index{
  3. protected

    $params

    =

    [

    ]

    ;
  4. function

    __construct(

    $params

    =

    [

    ]

    )
  5. {
  6. // Define provided parmaters
  7. $this

    ->

    params

    =

    $params

    ;
  8. }
  9. public

    function

    index(

    )

    {
  10. // Sample page content
  11. echo

    "<h1>Sample Index Page</h1>"

    ;

  12. // Output the prameters available
  13. echo

    "<pre>"

    ;
  14. print_r

    (

    $this

    ->

    params

    )

    ;
  15. echo

    "</pre>"

    ;
  16. }
  17. }

Users.php

  1. <?php

  2. class

    Users{
  3. protected

    $params

    =

    [

    ]

    ;
  4. function

    __construct(

    $params

    =

    [

    ]

    )
  5. {
  6. // Define provided parmaters
  7. $this

    ->

    params

    =

    $params

    ;
  8. }
  9. public

    function

    index(

    )

    {
  10. // Sample page content
  11. echo

    "<h1>User List Page!</h1>"

    ;
  12. echo

    "<pre>"

    ;
  13. print_r

    (

    $this

    ->

    params

    )

    ;
  14. echo

    "</pre>"

    ;
  15. }
  16. public

    function

    edit(

    $user_id

    =

    ''

    )

    {
  17. // Sample page content with the argument
  18. echo

    "<h1>EDIT USER with an ID of: [{$user_id}

    ]</h1>"

    ;
  19. }
  20. }

Great job! It's time to verify whether the routing system functions as intended.

To conduct a thorough examination of the application's functionality, please navigate to the following URLs:

Note: Replace [appName] with the name assigned to the folder containing your source code files on your system.



If you'd like to test request method mismatches, you can easily execute a curl command in your terminal or command prompt.

curl -X POST "http://localhost/[appName]/user/23"

DEMO VIDEO:

And there you have it! I hope that this PHP MVC Routing Implementation Tutorial will aid your comprehension of the routing system. Please don't hesitate to download the entire source code I've provided and make improvements as needed. You'll find the download button located beneath this article.

For additional Free Source Code, Tutorials, and articles, delve deeper into this website.

Happy Coding =)


Download
You must upgrade your account or reply in the thread to view the hidden content.
 

452,496

332,845

332,853

Top