Jump to content

Developer Documentation

Models

In an MVC application, the Model is responsible for interacting with data, and handing it to the Controller. This is no different in IPS4.

Generally speaking, an instance of a model refers to a thing. For example, if you had forums and topics, Forum would be a model, as would Topic. The model for each would then provide methods allowing you to interact with them. When designing models for your application, list the things your application works with - those are likely to be your models.

 

Name & location

A model name should always be a singular noun; that is, a model always refers to one thing. Model names should also always be PascalCase.

Models belong in the /sources folder of your application. As discussed in Autoloading, within /sources, you should have a subdirectory that takes the name of your model, with the model itself being inside that subdirectory (along with any supporting modules).

  • /sources/topic/topic.php - Incorrect: lowercase folder/model name
  • /sources/Topics/Topics.php - Incorrect: plural model name
  • /sources/Topic/Topic.php - Correct

Once again referring to the Autoloading guide, the classname within the PHP file should be prefixed with an underscore. For example, if your file was named Topic.php, the model class it contains should be named _Topic.

 

Base models

There are a few base models that your own models will frequently extend. Each will be discussed in more depth - including a full overview of the methods they provide - in their respective sections later in this documentation. The important ones are:

  • \IPS\Node\Model - Methods for working with nodes, a tree-like structure useful for things like categories (and much more)
  • \IPS\Content\Item - Methods for working with content items, e.g topics, gallery images
  • \IPS\Content\Comment - Methods for working with comments (including forum posts)
  • \IPS\Content\Review - Methods for working with reviews

These four base models all implement IPS4's Active Record pattern, providing a consistent interface for creating instances of your models and working with data within them.

 

Example

/exampleApp/sources/Counter/Counter.php
A very simple standalone model that provides a method for storing and incrementing a number.

<?php

namespace IPS\exampleApp;

class _Counter
{
	protected $counter = 0;

	public function incrementCounter ()
	{
		$this->counter++;
	}
}

 

/exampleApp/modules/front/example/index.php
A controller that creates an instance of the above model, then calls the incrementCounter method it provides.

namespace IPS\exampleApp\modules\front\example;

class _index extends \IPS\Dispatcher\Controller
{
	public function manage()
	{
		$myCounter = new \IPS\exampleApp\Counter();
		$myCounter->incrementCounter();		
	}
}

 


  Report Document


×
×
  • Create New...