The Models

Models are the objects used in order to perform CRUD operations. The models can be also objects that can contain or generate data.

Defining new models

You can define new models in the following way:

  1. Create a new model file inside "App / Model". The file name should have the first letter in uppercase (capitalized). As example the model file "fibonacci" should be saved as "App / Model / Fibonacci".

  2. The model class should have the prefix "Model_" following with the model name capitalized (only the first letter), so for example the class "fibonacci" should look like "Model_Fibonacci".

  3. The model class should extends from "Model".

If you followed the last 4 steps our new model should look like this:

    class Model_Fibonacci extends Model {}

Model instances

Every model can be instantiated in the two following ways:

  1. Just like a normal instance. Example:

    $fibonacci = new Model_Fibonacci();
  2. Using the factory method when the model extends from the "Model" class. Example:

    $fibonacci = Model::factory('fibonacci');

Full Example

This is our model:

    class Model_Fibonacci extends Model
    {

      /**
       * Computer and return the a sequence of Fibonacci numbers
       *
       * @param int   $limit
       * @return array
       */
      public function compute($limit = 10)
      {

        // Initialize sequence
        $sequence = [0, 1];

        do {

          $last_idx = count($sequence);

          // Compute fibonacci (Use the bcadd function for more precision)
          $sequence[] = $sequence[$last_idx - 2] +  $sequence[$last_idx - 1];

        } while ($last_idx <= $limit);

        return $sequence;

      }

    }

We can instantiate our new model from the controller using different ways:

    /**
     * Default controller entry-point
     */
    class Controller_Main extends Controller
    {

        /**
         * Entry point
         */
        public function action_main()
        {
            // Instantiate using the factory method
            $sequence = Model::factory('Fibonacci')->compute(10));

            // Or we can instantiate like a normal class
            /*
            $fibonacci = new Model_Fibonacci();
            $sequence = $fibonacci->computer(10);
            */

            print_r($sequence);
        }

    }