SoFunction
Updated on 2025-03-06

How to distinguish between application logic (Controller layer) and business logic (Model layer) in C# MVC mode?


class Controller_Cart
{
    function actionCheckOut()
    {
        Cart::instance()->checkout();
       
echo 'success';
    }
}
class Cart
{
    function checkout()
    {
// Start a database transaction
        ....
       
        try
        {
// Create a new order object
// $this->owner is the owner (user) of the current shopping cart
            $order = new Order($this->owner);
           
// Add all items in the shopping cart to the order
            foreach ($this->items as $item)
            {
                list($goods, $quantity) = $item;
                $order->add($goods, $quantity);
            }
// Save the order
            $order->save();
           
// Clear the shopping cart
            $this->items = array();
        }
        catch (Exception $ex)
        {
// An error occurred, rollback the transaction
            ....
              
// Rethrow the exception
            throw $ex;
        }
       
// Return to the newly created order
        return $order;
    }
}


class Order extends Model
{
    public $items;
  
    function add($goods, $quantity)
    {
        $this->items[] = array($goods, $quantity);
        return $this;
    }
  
    function save()
    {
        foreach ($this->items as $item)
        {
            list($goods, $quantity) = $item;
// When saving an order, reduce the inventory of each item in the order
            $goods->decrRemaining($quantity);
        }
       
// Call the save of the parent class
        parent::save();
       
        return $this;
    }
}