I was wondering what should I do with my entities? For example, a class named Articles, with a few datamembers (name/title/date) and getters & set开发者_高级运维ters. I could add these to my Articles datamember, but it's better practice to seperate those. So what do you think?
Thanks!
i usually do this:
1.- create my entity classes in /system/application/classes
class MyEntity {
}
2.- define a constant to point to that folder on /system/application/config/constants.php
define('CLASSES_DIR', APPPATH . "classes/");
3.- include the entities classes from the models:
require_once(CLASSES_DIR . "MyEntity.php");
class MyModel extends Model {
function test() {
$entity = new MyEntity();
$entity->doSomeStuff();
}
}
That won't break your mvc structure, and keeps for entities classes separated. Hope that helps!
I liked @ilbesculpi's solution, but I customized it a bit using a namespace rather than using a constant and require_once
. Here is my version:
1) Create my entity classes in /system/application/entities.
namespace MyApplication\Entities;
class ArticlesEntity
{
function doSomeStuff()
{
// Your code here...
}
}
2) Include my entity class in my model via a using
statement.
use MyApplication\Entities\ArticlesEntity;
class ArticlesModel extends CI_Model
{
function test()
{
$entity = new ArticlesEntity();
$ArticlesEntity->doSomeStuff();
}
}
CodeIgniter models use the singleton pattern. You can create libraries or use $foo = new Some_Model if you like, remember that its all just PHP :)
精彩评论