understanding MVC

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
gautamz07
Forum Contributor
Posts: 331
Joined: Wed May 14, 2014 12:18 pm

understanding MVC

Post by gautamz07 »

given the below snippet : ()


index.php in main directory

Code: Select all

<?php 

	$url = $_GET['url'];

	echo $url;


	require 'controllers/' . $url . '.php';

	$controller = new $url;
?>

index.php in controller

Code: Select all

<?php


	class Index
	{
		
		function __construct()
		{
			echo "We are in Index";
		}
	}

?>

in my browser i see the following (i.e if i type ... mypath/index):

We are in Index.

now i don't quit e understand this line :

$controller = new $url;

what is the above line doing ?

is it instantiating $controller with a new instant of $url

or is it calling the class directly to which $uri corresponds to ???
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: understanding MVC

Post by Celauran »

It's assuming $url is going to be a valid controller, requiring the file from the controllers directory -- which means the whole thing will come crashing down if it doesn't exist -- and then instantiating the class.
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: understanding MVC

Post by Christopher »

You index.php is specifically a Front Controller which routes requests. Your controllers/index.php is an Action Controller which is typically what is meant by the "C" in MVC. The Controller's job is inspect the Request and then connect the Model and the View so that they can generate the Response.

The code above is using a scheme referred to as Convention over Configuration. The convention used here is a common one for MVC: the parameter value, the file name and the class name are all the same or derivable.
(#10850)
User avatar
gautamz07
Forum Contributor
Posts: 331
Joined: Wed May 14, 2014 12:18 pm

Re: understanding MVC

Post by gautamz07 »

Thanks Guys . :)
Post Reply