I've been trying to understand MVC with sites like phpPatterns. I haven't got any books yet, but I think I have the basic idea. So anyway, below is my attempt at an MVC for an update profile script. I decided the Front Controller is Apache coupled with mod_rewrite, and the Page Controller is update-profile.php coupled with an UpdateProfileController class.
I don't think I could have gone wrong with my design, since it's so shallow right now, but I'm frustrated with how to deal with errors. The code right now:
Code: Select all
<?PHP
#update-profile.php
$request = new Request(); //give it post, get, whatnot
$response = new Response();
$controller = new UpdateProfileController();
if ( isAnError( $error = $controller->checkUserPermissions(
new UserPermissions( $request->getCredentials() )
) )
)
{
$response->setHeader( $error->getHeader() );
$response->setContent( $error->getView() );
$response->send();
exit;
}
$controller->setModel(
new UpdateProfileModel( $request->getPostData() )
);
$controller->setView ( new UpdateProfileView() );
//response will get the correct template output from the UpdateProfileView() in getView()...
//this way, we could come back later and have it output XML or something
//simply by telling $response we want XML output back
//and the response would ask the view object for XML output
$response->setContent( $controller->getView() );
$response->send();
exit;
?>Code: Select all
class PageController()
{
/* setModel, setView, getView... */
}
class UpdateProfileController extends PageController
{
function checkUserPermissions($permissions)
{
if ( $permissions->isUserAuthenticated() == false )
{
return new UnauthenticatedUserError(); //would extend class Error, which would extend class PageController
}
return true;
}
}
function isAnError($object)
{
return is_a( (object) $object, 'Error');
}
I don't want to use any local handling inside the checkUserPermissions() method, because
1. I'd possibly have to globalize $response inside the class, or give it the $response object,
2. I couldn't "ignore" the exception without modifying the Controller class, and
3. It'd mess up the code flow in update-profile.php, because it wouldn't be obvious how we're dealing with non-credentialed users by just looking at update-profile.php. You'd have to go look at the innards of UpdateProfileController.
Still, the "if ( isAnError( $error = $controller->checkUserPermissions( new UserPermissions( $request->getCredentials() ) ) )" line seems totally clunky.
Any ideas or thoughts?
- Nathaniel