How to deal with Class not found with composer - php

I installed composer and laravel and installed some packages
all work fine, but now I created my own class under the folder services
I gave it name space of Services like that:
namespace Services;
And the class name is UploadToImgurService
I run the composer command:
composer dump-autoload
And in my controller I wrote:
use Services\UploadToImgurService;
But I get this error:
Class 'Services\UploadToImgurService' not found
What did I did wrong?
Is there anything else that I should do with composer for autoloading the service class?
EDIT
I found a solution
I edited y composer.json file and added to psr-4 the line
"Services\\" : "app/services"
But why It didn't workt before? The line :
"App\\": "app/",
was there, maybe it loaded the class but under the app namespace?

If you are using a case sensitive file system, you will need to have the Services folder with upper case S.

Your idea is right, but let me try to explain how the psr-4 autoloading works.
You can define root namespaces in your composer.json file and map it to any project directory. Inside the defined directories, your classes should get the root namespace. The namespace segments after the root are build by your sub directory structure and the class name is equal to the file name (PSR-4 Autoloading).
E.g
"MyNamespace\\WithSubNamespace\\": "cool/project"
cool/project/MyClass.php -> MyNamespace\WithSubNamespace\MyClass
cool/project/SubDirectory/AnotherClass.php -> MyNamespace\WithSubNamespace\SubDirectory\AnotherClass
In Laravel, the app directory is mapped to the App namespace as default. Optionally, you can change the root namespace with the command php artisan app:name [NewRootNamespaceName], but the autoloader only finds classes inside the app directory.
If you create a new directory outside of "app", you have to add the directory to your psr-4 namespace mapping in the composer.json file.
In your example, you define a new root namespace in the existing app directory, so your issue was that the root namespace was unknown and you solved it by adding the line in your composer.json.
This is possible, because psr-4 provides a huge flexibility. But personally, i would not recommend to use different root namespaces in the same project.
I hope i could help and maybe this is also interesting for you: composer.json PSR-4.

maybe you forgot to add this line of code
require_once('vendor/autoload.php');

Once I was getting the error:
Fatal error: Uncaught Error: Class "..." not found
in /var/www/html/... on line ...
I was requiring autoload file this way:
require 'vendor/autoload.php';
After I changed the line to:
require __DIR__.'/vendor/autoload.php';
it started working...
Weird, since the the vendor folder was in the same directory as the file which was calling it.
BTW, I was using Composer 2 and PHP 8.1.

Related

Composer autoload in Wordpress custom plugin

I'm developing a brand new Wordpress plugin and I would like to use Composer to autoload classes.
Here is the plugin directory heriarchy:
my composer.json content:
{
"autoload": {
"psr-4": {
"G4S_ECommerce\\": "src"
}
}
}
In the directory where composer.json is, on cmd, I execute:
composer install -> this generates the vendor/composer folder and the vendore/autoload.php.
composer composer dumpautoload -o -> outputs "Generated optimized autoload files containing 0 classes"
In the main file G4S_Ecommerce.php I put the following line:
require __DIR__.'/vendor/autoload.php';
In the same file I put
use G4S_Ecommerce\Includes\Ecommerce;
$starter = new Ecommerce();
but it leads me to a Fatal error: Uncaught Error: Class 'G4S_Ecommerce\Includes\Ecommerce' not found
Why the composer dumpautoload -o returns 0 classes? What am I doing wrong?
Thanks
First (it is not obvious from your files structure) you need to set a namespace for your Ecommerce class (i.e., G4S_Ecommerce/Includes)
Second, based on what you've declared in the autoload directive, composer is expecting to find the G4S_Ecommerce folder under the src folder, and in that folder you need to place your php class file with a name identical to the class name (i.e., Ecommerce).

Symfony4 Error loading classes custom folder "Expected to find class... but it was not found"

Problem
I'm trying to setup a custom directory structure
for some shared classes in my Symfony project. I
want to create a custom folder in the root of my
project and I want to use the Symfony auto-load
feature to automatically register services from
that folder.
So I added a custom services namespace to the
services.yaml file:
# src ./config/services.yaml
services:
...
TestNamespace\:
resource: '../TestNamespace/*'
...
And I added an empty class in the custom folder:
# src ./TestNamespace/TestClass.php
namespace TestNamespace;
class TestClass
{
}
When I run the app I get the following error:
(1/2) InvalidArgumentException
Expected to find class "TestNamespace\TestClass" in file
"/path/to/ClassLoadErrorDemo/demo/TestNamespace/TestClass.php"
while importing services from resource
"../TestNamespace/*", but it was not found! Check the
namespace prefix used with the resource.
(2/2) FileLoaderLoadException
Expected to find class "TestNamespace\TestClass" in file
"/path/to/ClassLoadErrorDemo/demo/TestNamespace/TestClass.php" while
importing services from resource "../TestNamespace/*", but it was not
found! Check the namespace prefix used with the resource in
/path/to/ClassLoadErrorDemo/demo/config/services.yaml (which is loaded
in resource "/path/to/ClassLoadErrorDemo/demo/config/services.yaml").
I double checked the paths, namespace and the class
name multiple times and everything seems fine and I
don't understand why I still get the error.
Controllers in the ./src folder seem to load fine.
What am I doing wrong here?
Steps to reproduce
I created a demo repo to isolate the problem.
git clone https://github.com/smoelker/SymfonyClassLoadErrorDemo.git
cd SymfonyClassLoadErrorDemo/demo
composer install
mv TestNamespace/TestClass.php_ TestNamespace/TestClass.php
php bin/console server:start
Update your composer.json autoload setup
{
[...]
"autoload": {
"psr-4": {
"TestNamespace\\": "TestNamespace/",
"": "src/"
}
},
[...]
}
After run: composer dump-autoload and try again.
composer dump-autoload --classmap-authoritative will only work if your src directory is present at the time you run the command.
This can be an issue with multi-stage Docker builds in particular, when you are normally only copying the composer.json/composer.lock into the build image.

Composer not auto-loading required classes

I'm new to Composer and I'm really struggling to auto-load my classes with composer. What am I missing in the following process?
I installed the package in my PHP includes folder (which is outside the document root - I'm not sure if that matters) like this:
composer require monolog\monolog
It stated it completed successfully and I confirmed the project was added to my vendor folder.
My entire composer.json file looks like this:
{
"require": {
"monolog/monolog": "^1.22"
}
}
My entire test file looks like this:
<?php
require_once "vendor/autoload.php";
use Monolog\Logger;
$log = new Logger("name");
?>
And I get this error when I load the page:
Fatal error: Uncaught Error: Class 'Monolog\Logger' not found in C:\Dropbox\Projects\Web\Websites\Instamation\wwwroot\qbtest.php:6 Stack trace: #0 {main} thrown in C:\Dropbox\Projects\Web\Websites\Instamation\wwwroot\qbtest.php on line 6
It includes the vendor/autoload.php file without any error.
I've tried to run these commands in composer without any change:
composer update
composer dump-autoload -0
I've also tried it with different packages and I get the same error, so I'm pretty sure it has nothing to do with the monolog package.
Is there a step here I'm missing? I don't need to manually define which classes to autoload in a json file if I require them in composer, do I?
Edit 1:
As requested, here's the paths to my different files.
Path to the test page:
C:\Dropbox\Projects\Web\Websites\Instamation\wwwroot\qbtest.php
Path to the composer.json file (outside the document root but in my includes path):
C:\Dropbox\Projects\Web\Websites\Instamation\wwwincludes\composer.json
My vendor folder is here:
C:\Dropbox\Projects\Web\Websites\Instamation\wwwincludes\vendor\
And inside my vendor folder I have these folders and file:
bin/
composer/
monolog/
psr/
autoload.php
You need to include autoload in your qbtest.php as following:
require_once "../wwwincludes/vendor/autoload.php";
use Monolog\Logger;
$log = new Logger("name");

How do I require a file or class in a vendor library in Yii2 that is not already included?

I have this class that Yii2 cannot see. All the other classes work. I tried the following. The commented lines did not work.
// use app\vendor\googleads\googleads-php-lib\src\Google\Api\Ads\Common\Util\ErrorUtils;
// require_once UTIL_PATH . '/ErrorUtils.php';
require_once('../vendor/googleads/googleads-php-lib/src/Google/Api/Ads/Common/Util/ErrorUtils.php');
use \ErrorUtils;
This works, but it doesn't look right. Also it doesn't work in the command mode, which I need.
$ yii cron
PHP Warning: Uncaught exception 'yii\base\ErrorException' with message 'require_once(../vendor/googleads/googleads-php-lib/src/Google/Api/Ads/Common/Util/ErrorUtils.php): failed to open stream: No such file or directory' in /cygdrive/c/Users/Chloe/workspace/xxx/models/GoogleAdWords.php:36
How can I require or use this class in Yii2?
Fisrt addto composer (shell command):
$ composer require googleads/googleads-php-lib
Then simply use te class:
\ErrorUtils::GetApiErrors($var);
Note that googleads don't use namespaces so it's "\" NS
The library that you use doesn't provide psr-4 autoloader settings for its classes. You need to add autoload classmap for classes that you want to load, into your composer.json in project's root directory like following:
"autoload": {
"classmap": [
"vendor/googleads/googleads-php-lib/src/Google/Api/Ads/Common/Lib",
"vendor/googleads/googleads-php-lib/src/Google/Api/Ads/Common/Util"
]
},
and then in your console: composer dump-autoload
This will update the composer autoloader. After that you'll be able to call library classes with: \ErrorUtils::GetSourceOperationIndex($error)

PSR-4 autoloading with Composer

I run a portail with composer's autoloading class system:
"autoload": {
"psr-4": {
"Portal\\": "src/"
}
}
It works when I run composer.phar dump -o, for instance my class Boostrap is well referenced into vendor/composer/autoload_classmap.php file:
'Portal\\Core\\Bootstrap' => $baseDir . '/src/core/Bootstrap.php',
But when I don't run the optimized option on autoload dumping, the autoloading system doesn't works anymore:
Fatal error: Class 'Portal\Core\Bootstrap' not found in /var/www/portail/prod/web/index.php on line 7
How can I make autoloading works without -o option?
There are two ways to fix it.
change composer.json to
"Portal\\Core\\": "src/core/"
Or rename the core directory to Core
https://getcomposer.org/doc/04-schema.md#psr-4
The subdirectory name MUST match the case of the sub-namespace names.
http://www.php-fig.org/psr/psr-4/

Categories