I was on my paypal account and noticed the url. cmd=something. Sweet, a command! It's telling the script to do something. So I don't know why this just now clicked in my head, but that command is controlling what the script executes and displays.
Usually, procedurally, I will just use an if/else/elseif on the $_GET['cmd'] or whatever other variable I'd be using. But I kept thinking about the word control. This command (or any parameter really.. this just happened to be the first one that clicked for me) could be used to design a controller (I think...).
So, I wrote this. It's very elementary and straight and to the point (but hey, im learning), and it could use better use of __get() and __set().. but you will get the idea.
Code: Select all
<?php
class command
{
private $_command;
private $_validCommands;
private $_defaultCommand;
public function setValidCommands($commands)
{
$this->_validCommands = $commands;
}
public function setDefaultCommand($command)
{
$this->_defaultCommand = $command;
}
public function setCommand($command)
{
$this->_command = $command;
}
public function getCommand()
{
return in_array($this->_command, $this->_validCommands) ? $this->_command : $this->_defaultCommand;
}
}Code: Select all
//instantiate the object
$cmd = new command();
//set allowed commands
$allowedCommands = array('create', 'edit', 'view');
$cmd->setValidCommands($allowedCommands);
//set current command
$cmd->setCommand($_GET['cmd']);
//do something with this....?
$model = new model($cmd->getCommand());Any comments you could add on this would be appreciated, really. When something clicks with me I get all excited and research/code writing happy.