G
G
gallantalex2017-01-11 21:49:20
PHP
gallantalex, 2017-01-11 21:49:20

Namespace and class connection?

Started making a web application on Slim.
I can't figure out why the namespace doesn't work.
There is a standard autoload.php in the Vendor folder. In index.php I include it via require. Now I create a ClientsController class in the classes/ClientsController.php file and declare the Controllers namespace. Then in the calling file I write use Controllers as Contrl and call
$myControl = new Contrl\ClientsController;
And it says:
Fatal error: Class 'Controllers\ClientsController' not found in C:\xampp\htdocs\goodfood\public\index.php on line 20
What exactly am I doing wrong?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Maxim, 2017-01-11
@gallantalex

Yuri is right, only in your case you need not "App: src/" folder, but "App: classes/", i.e. the root of your sources. And arrange the files according to the specified PSR-0. ( www.php-fig.org/psr/psr-0 )
You can also use PSR-4 ( www.php-fig.org/psr/psr-4 ) there are slightly different rules.
For example, I do this:

"autoload": {
    "psr-4": {
      "Appname\\": "src/"
    }
  }

Accordingly, the code is located in the src folder with the following structure (This, by the way, is just a Silex project.):
src/
--Appname/
----Controller/
------IndexController.php

The controller will have it namespace Appname\Controller;
And using it like use Appname\Controller\IndexController as Control;
this also helps to update the autotrapcomposer dump-autoload -o

Y
Yuri, 2017-01-11
@riky

in the composer.json file, you need to register autoload.

"autoload": {
        "psr-0": {
            "App": "src/"
        }
    },

and update
composer update
all classes in the App namespace will be loaded from the src folder.

G
gallantalex, 2017-01-12
@gallantalex

Another small incomprehensible moment:
Why does everything work for me in the public/index.php file:

use Controller\ClientsController;

$myControl = new ClientsController();
$myControl->hello();

and if I connect instead of this initialization an auxiliary file with a similar code:
Then the ClientsController class is not in it? In fact, the code of the all.php file is inserted into index.php and everything should work fine, does the path really affect this? What's the catch?
Project structure:
-public/
--index.php
-src/
--routes/
---all.php

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question