I'm bored, and I think this is really cool, so I just wanted to show you some code snippets from my CMS.
Check out my login form at http://www.keithdevens.com/admin/. Here's the code that produces that:
<?php
#the login function is part of my Administration class,
# which is beyond the scope of this post :)
function login(){
global $cms;
if(!$a = &$cms->getAction('administration.logIn')){
echo "<p>Couldn't get login action</p>";
}else{
$cms->incLibrary('formhelper');
$fh = &new HtmlFormHelper($a);
$fh->setWidget('password',HTMLFORMHELPER_PASSWORD);
$fh->printDefaultForm('Log in');
}
}
?>
Get rid of the obvious error handling and setup code and that's four lines. Now, for the "action" itself:
<?php
class administration_logIn extends Action{
function construct(){
$this->setActionName('administration.logIn');
$this->addField('username',array('title'=>'Username','required'=>true));
$this->addField('password',array('title'=>'Password','required'=>true));
}
function validate(){
global $cms;
$a = &$cms->getModule('authentication');
if(!$a->validateLogin($this->get('username'),$this->get('password'))){
$this->addError('Your username/password combination did not validate');
return false;
}else{
return true;
}
}
function process(){
global $cms;
$a = &$cms->getModule('authentication');
$a->logIn($this->get('username'),$this->get('password'));
}
}
?>
I never want to go back to writing forms the "old" way again.
Obviously, there's a lot of other code behind the scenes. My CMS intercepts any posted Actions and passes request data to them, and then you have the authentication module which keeps track of your username and user_id and maintains that info in a session. And of course you have the Action base class, and the HtmlFormHelper class. All of said code I may make available someday. The point is that the interface is simple. It rules.
Hey, Keith implies he gave me the idea. No fair!
You may have been thinking about the idea before me, I dunno, but I've been wanting an easier way to do HTML forms for ages.[1]
Actually, when we had last talked about it, I was trying to do the form thing simply by abstracting away the code that would print the form HTML into functions. I later got the idea to make a form "model" (the Action) that can represent every type of form possible
So I separated the HTML generation from the form definition, validation, and processing, and that worked really well.
Footnotes:
[1]: More importantly, however, this makes it easier to do HTML forms correctly. It can actually be pretty hard to write a correct Action, but once you do, it's correct, and not mingled with all your HTML. No more writing <input type = "radio" <?php if($value == $foo){echo 'checked = "checked";}?> value = "<?php echo $foo;?>" /> all the time, hooray!
Just wondering, do you have plans to release this CMS code as open-source? It looks pretty awesome to me.