MySQL and more

Saturday, November 17, 2012

Tiny PHP MVC

I'm not the first, but this is what I've been using to kickstart php based projects.

1. Save this code as index.php
2. Create a views directory
3. Call the script with index.php?action=method
4. Create new actions by adding public methods to the Controller class

<?php
error_reporting(E_ALL);

// default action; use example.com/script.php?action=blah to control which function to call
$action = 'index';
if (isset($_GET['action']))
{
 $action = $_GET['action'];
}

// create the controller and call the requested action if possible
$controller = new Controller();
if (is_callable(array($controller, $action )))
{
 $controller->$action();
}
else
{
 print "Invalid action ($action)";
}
exit; // and we're done

// helper function
function site_url()
{
 return $_SERVER['SCRIPT_NAME'];
}

/**
 * basic controller class, any public method will be accessible via script.php?action=method
 */
class Controller
{
 private $model;
 
 function __construct()
 {
  // create an instance of any models used
  $this->model = new Model();
 }
 
 public function index()
 {
  include "views/header.php";
  
  // get data from our model
  $message = $this->model->get_message();
  
  // the template will have to know we create the $message variable here
  require "views/index.php";
 }
}


/**
 * simple model class, handles getting data for the controller
 * This could use database connections, or other methods
 */
class Model
{
 public function get_message()
 {
  return "Hello World";
 }
}
?>

1 comment:

August said...

Good stuff! I do something similar with my sites, but, in your case, there's a security risk if you accidentally forget to privatize a method. That method is now accessible via the web, and has the potential to do all kinds of damage.

I recommend adding "_action" to all public action methods. Then, in your routing, you just look for $action . '_action'.

Not only is this much safer, when looking at a controller it's a whole lot easier to see which methods are accessible via the web.

Followers