Ajouve
Ajouve

Reputation: 10089

include files in mvc model php

I create my own mvc model, so I have to include all my models and controllers class.

For the moment each time I need a model in a controller I use:

require_once('myModel.php');

A little like import in java

But I have a question, is it a good solution to continue on this way ? I would prefer include all my models and controllers at the beginning of the code but I'm afraid this solution is too heavy.

Thanks

Upvotes: 1

Views: 3155

Answers (2)

Aurimas Ličkus
Aurimas Ličkus

Reputation: 10074

Generally i would not recommend you to create your own framework, but if you insist or want to do it for learning purposes the PHP community created FIG (Framework Interop Group) to maintain consistency between frameworks, and how things should be handled.

The problem you are trying to solve is called autoloading, it's also documented AS PSR-0 standard, https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md, Have a nice read.

And here is PSR-0 compliant autoloader examples: PHP - most lightweight psr-0 compliant autoloader

Basically it means that your namescape path will tell where to look for file.

For example you want to get BussinessObject in bootstrap.php:

//MVC/Models/BussinessObject.php

namespace MVC/Models;

class BussinessObject {

}

//MVC/bootstrap.php

namespace MVC;

use MVC/Models/BussinessObject;

$BussinessObject = new BussinessObject()

Then autoloader will look for file in MVC/Models/BussinessObject.php, and calls require using that path.

Upvotes: 3

d.grassi84
d.grassi84

Reputation: 393

The best approach should be to include files only when they are really needed. As this isn't often practical, you should try to include on app init only the files containing the basic functions you use.

Upvotes: 0

Related Questions