Rewrite engine with procedural method on OOP. I create several classes at the beginning of each write

namespace ... use ... 

I get errors class not found . Tell me how to organize autoloading classes, for example, using Composer. Is it possible to automatically generate composer.json for your project?

Before that, I used it only to connect third-party libraries.

    2 answers 2

    When you connect the composer to your project instead

     require "../vendor/autoload.php"; 

    write

     $loader = require "../vendor/autoload.php"; $loader->setPsr4('ВАШ_NameSpace\\', 'ПУТЬ_ДО_КОРНЯ_ВАШЕГО_NameSpace'); 

    After that, the composer picks up your classes too.

    • What for? After all, you can specify this in composer.json itself. - cronfy
    • @Visman, sort of figured out a bit. I made the connection of the settings file, constants are set in it (they are all transmitted normally), but if you set any variable, then it cannot be turned to it from another file. Do not tell me what the problem is? - Dmitriy
    • @Dmitri, with OOP there should not be global variables. Variables must be passed explicitly, for example, when creating an instance of a class or calling a method. Or store them in a repository that is accessible from any class. Singleton can be used as a repository. Stackoverflow.com/questions/92217/… - Visman
    • @Visman, I did not expect the variable to be global, I just figured that composer autoload does exactly the same thing as if I just require_once the settings file. Accordingly, I would have drilled a piece of code from another file. it turned out that this is not quite the case, and the constants became global, but the variable remained to live inside the config. As for the singleton, I'm not sure that it is implemented in Smarty itself. So sculpt a class that will follow this. Although maybe someone else uses template engines? - Dmitriy
    • @ Dmitry, with Smarty did not work, but judging by the documentation smarty.net/docsv2/ru/api.assign.tpl you need to use the assign () method to transfer variables to the template. You can transfer not only a simple variable, but also an array and an object. - Visman

    If you use Composer, then write the settings of the connected files or folders in composer.json .

    Official documentation:

    There is a small article in Russian on this topic: