Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP autoload MVC

Tags:

php

autoload

I came across the __autoload function in PHP and would like to use it with my MVC folder structure. The function itsself is pretty easy, but how do I achieve a dynamic folder scanning after some kind of naming, please see example:

-application
--controller
--models
---entities
----house
---factories
----houseFactory
--views
-library
-public

As you maybe recognise its very close based on zend framework or other frameworks -as I come from those, however I would like to develop a website without framework and just started to write bootsrap file.

Maybe sombody could help me with the autoload in this - i think - advanced usage.

My Classnames will be like Model_Entities_House or Model_Factory_HouseFactory

witch can be applied to the folder structure.

like image 463
Richard Avatar asked Oct 28 '25 21:10

Richard


1 Answers

What I do mostly is use the SPL autoload function, which will help you to accomplish this quite easily. It should be something like this:

spl_autoload_register("MyClass::Autoloader");

Then, you can do something like this

class MyClass
{
  public static function Autoloader($className)
  {
    //parse $className and decide where to load from...
  }
}

If you´re using a naming convention, then you should be available to load the required file by just using the name.

like image 100
David Conde Avatar answered Oct 30 '25 11:10

David Conde