<?php
class CartController extends AppController
{
/**
* Add a product to the shopping cart.
*/
public function add_product($id)
{
$cart = new CartModel();
$cart->addItem($id); // Updates the PageModel stack (session)
$page = new PageModel();
$next = $page->popPage();
switch($next->result) {
case 'redirect':
$this->redirect($next->url);
break;
case 'render':
$this->render($next->view);
break;
}
}
public function details()
{
// ... display cart details ...
}
}
class CartModel extends AppModel
{
public function addItem($id)
{
$user = new UserModel();
$page = new PageModel();
if (!$user->loggedIn()) {
$page->pushPage('redirect', "cart/add_product/$id");
$page->pushPage('redirect', "user/login");
return;
}
// ... add item to the database ...
$page->pushPage('render', 'cart_details.tpl');
$page->message = 'Item has been successfully added to your cart.';
}
}
class UserController extends AppController
{
/**
* User login form
*/
public function login()
{
$page = new PageModel();
$user = new UserModel();
if ($_POST) {
// ... code goes here to check password
if ($login_ok) {
// ... if login is ok, continue
} else {
// ... if login failed, stack the form on the view again
$page->message = 'Invalid username or password. Try again.';
$page->pushPage('render', 'login_form.tpl');
}
}
$next = $page->popPage();
switch($next->result) {
case 'redirect':
$this->redirect($next->url);
break;
case 'render':
$this->render($next->view);
break;
}
}
}
class PageModel extends AppModel
{
public function pushPage($type, $target)
{
// ... add page to top of stack
}
public function popPage()
{
// ... get page (and remove) from top of stack
}
}
/**
* Summary: When the user attempts to add an item to the shopping cart and they are
* not logged in, we push a login page onto the page stack. They go to the login
* page and fill it out. If the login fails, the form is pushed onto the stack. If
* the login succeeds, we automatically go back to attempting to add the item to the
* shopping cart. This time, the user is logged-in so it will be successful.
*/