At the moment, I hook up like this:

$model_name = 'Model_'.$controller_name; $controller_name = 'Controller_'.$controller_name; $action_name = 'action_'.$action_name; // подцепляем файл с классом модели $model_file = strtolower($model_name).'.php'; $model_path = "application/models/".$model_file; if(file_exists($model_path)) { include "application/models/".$model_file; } 

Based on this design, I can only hook up to the controller a model with the same name, but it became necessary to use another model (with a different name), so how to do it? In general, I will explain in more detail what I want to do: I use the mvc pattern, I created a controller for the page template and created a model for it that lists categories, these categories should be available on any page, so I added it to the template:

 class Controller_Template extends Controller { function __construct() { $this->model = Model_Template::get_data(); $this->view = new View(); } function action_index() { $data= Model_Template::get_data(); $this->view->generate('main_view.php', 'template_view.php', $data); return true; } 

So now I need to use this model (Model_Template) to get data on other pages, how can this be implemented?

  • Give the code to create a controller, please. - Igor Karpenko
  • I can write an example where we set the name of the model that is additionally required in the controller. Or in the main model. It will be with unlimited amount. If this option suits you. - Shadow33

3 answers 3

In PHP, there is a ready-made functionality for this. Called automatic loading classes. Detailed information and examples are in the documentation: autoload

The simplest use case. Determine the function __autoload

  function __autoload($class_name) { ... } 

Later, when you try to create an object of a class, this function will be called with the name of the class as an argument.

And then, depending on your tasks, you determine which file to include.

And although I do not approve of using static methods, this function works for them too. Only need to force a loader. For example, using the class_exists function first

    Maybe you should use the Factory pattern? Here is an example of application based on your code:

     <?php class ModelFactory { /** * Метод для загрузки модели * @param type $model_file * @throws Exception */ public static function build($model_file) { try { $model_path = "application/models/" . $model_file; if (file_exists($model_path)) { include "application/models/" . $model_file; } else { throw new Exception("Файл модели отсутствует"); } /** * После подключения файла с моделью, Вы можете сразу создать объект загружаемой модели и сразу его вернуть. * Например : * $model = new $model_file; или можете передать в этот метод еще одну переменную с названием класса модели и создавать объект используя другую переменную * return $model */ return true; } catch (Exception $e) { throw $e; } } } 

    With this code you can upload any files from the application/models/ folder. And if you want to change the folder, you can, for example, add another variable to the build method in which to pass the path to the folder where you need to look for the model.

    • I use mvc, I am not familiar with the factory - Denis
    • try-catch-throw? - etki
    • @Etki yes, exactly, since I don’t know exactly where exceptions will be handled. If it is not immediately in the factory, but somewhere above the level, then push the exception higher. - S. Pronin
    • one
      @Denys then I advise you to read the PHP book Matt Zandstra: objects, patterns and programming techniques. ) - S. Pronin

    If anyone is interested, he did it differently: the $data variable was entered into the session in the Main controller: $data = $_SESSION['gettypes']; and connected to the view template. The option is not perfect, but the problem is solved.