Autoload Class not found - php

I can't seem to figure out why i keep getting this error even though everything seems correct.
My Composer.json looks like this:
{
"autoload": {
"psr-4": {
"Datechecker\\": "lib/",
"App\\": "app/"
}
}
}
And my class looks like this:
<?
namespace Datechecker;
class App
{
public function runCommand(array $argv){
$name = "World";
if(isset($argv[1])){
$name = $argv[1];
}
echo "Hello $name!!!\n";
}
}
Then my executable file looks like this:
#!/usr/bin/php
<?
require_DIR_.'/vendor/autoload.php';
if (php_sapi_name() !== 'cli') {
exit;
}
use Datechecker\App;
$app = new App();
$app->runCommand($argv);
?>
I have tried to follow similar questions which i came across on here but none of the solutions seem to be working for me. Please help.
Update
Classes structure looks like this:
lib/
App.php
app/
vendor/
composer/
...
autoload.php
datechecker
composer.json

Related

PSR4 not working?

Class not found, apparently. I've tried various things but nothing works.
Composer:
"autoload": {
"psr-4": {
"App\\": "application/"
}
}
File structure:
https://i.imgur.com/h9wOEqI.png
<?php
namespace App\Library\Classes;
defined('START') or exit('We couldn\'t process your request right now.');
class Application
{
private static $libraries = array();
public static function get($library) {
if (isset(self::$libraries[$library]) && isset(self::$classes[$library])) {
return self::$libraries[$library];
}
$fixedLibrary = str_replace('.', '/', $library);
$file = ROOT . '/application/library/classes/' . strtolower($fixedLibrary) . '.php';
self::$libraries[$library] = $library;
$declared = get_declared_classes();
$workingClass = end($declared);
self::$libraries[$library] = new $workingClass();
return self::$libraries[$library];
}
}
?>
Error is on this line:
Application::get('test')->test();
Yet, if I change it to this, it works:
include ROOT . '/application/Library/Application.php';
App\Library\Classes\Application::get('test')->test();
The PSR4 is not built-in part or PHP, you need an implementation of autoloader to use this standard such as provided by the Composer.
When you install or update depedencies, composer generates the relevant code of autoloading, but you can directly update it by the command dump-autoload, as #jibsteroos said. Next you should explicitly include the file vendor/autoload.php in the entry point of your application.
Also, error message says about class Application, but you should add the use statement at first:
use App\Library\Classes\Application;
Application::get('test')->test();
Or use the fully qualified class name (class name with namespace prefix):
\App\Library\Classes\Application::get('test')->test();

php:composer auto loading not working with multiple directories inside src folder

Here is my folder structure
in my package/index.php look like this
require_once 'vendor/autoload.php';
use HelloWorld\SayHello;
use Test\First;
//works fine
SayHello::world();
//returns classnot found error
First::sayTest();
In my composer.json' i've included the following.
"autoload": {
"psr-0": {
"HelloWorld": "src/"
}
}
But i got the following error in First::sayTest() line
Fatal error: Uncaught Error: Class 'Test\First' not found
But the class First.php exists under src\Test folder.
namespace Test;
class First
{
public static function sayTest()
{
echo 'test';
}
}
You only declared that one prefix resides in src. Add another one:
"autoload": {
"psr-0": {
"HelloWorld": "src/",
"Test": "src/"
}
}
Also note that when you are using namespaces, PSR-4 is better suited:
"autoload": {
"psr-4": {
"HelloWorld\\": "src/HelloWorld/",
"Test\\": "src/Test"
}
}
your composer.json contains some entry, which makes it load HelloWorld, but there is no such entry for the folder "Test".
Maybe it would help to copy your First.php to the HelloWorld-folder and change your reference in package.index.php.
Change composer.json to read:
"autoload": {
"psr-4": {
"": "src/"
}
}
Then run composer dump-autoload to regenerate vendor/autoload.php.
Read more about the autoload section of composer.json.

how to use an autoloader in php

I'm new to PHP and not really familiar with using git.
I got this library:
https://github.com/CKOTech/checkout-php-library
and I wanna run the sample code here:
https://github.com/CKOTech/checkout-php-library/wiki/Tokens
I know the code may not work perfectly for you cuz you would need a secret key from the provider, however, I don't need general errors like " cannot find class ApiClient"
what I did is simply including the autoloader in my index.php file, is that all what I have to do to use an Autoloader? does it have to do anything with composer.json?
Thanks a ton for the help in advance.
Autoloader.php:
<?php
function autoload($className)
{
$baseDir = __DIR__;
$realClassName = ltrim($className, '\\');
$realClassName = str_replace('\\',DIRECTORY_SEPARATOR,$realClassName );
$fileName = '';
$includePaths = $baseDir.DIRECTORY_SEPARATOR.$realClassName. '.php';
if ( $file = stream_resolve_include_path($includePaths) ) {
if (file_exists($file)) {
require $file;
}
}elseif(preg_match('/^\\\?test/', $className)) {
$fileName = preg_replace('/^\\\?test\\\/', '', $fileName);
$fileName = 'test' . DIRECTORY_SEPARATOR . $fileName;
include $fileName;
} else {
$classNameArray = explode('_', $className);
$includePath = get_include_path();
set_include_path($includePath);
if (!empty($classNameArray) && sizeof($classNameArray) > 1) {
if (!class_exists('com\checkout\packages\Autoloader')) {
include 'com'.DIRECTORY_SEPARATOR.'checkout'.DIRECTORY_SEPARATOR.'packages'.DIRECTORY_SEPARATOR.'Autoloader.php';
}
}
}
}
spl_autoload_register('autoload');
If you want to use an autoloader to make your life measurably better:
Use namespaces/PSR4.
Use Composer.
So let's say I'm working on project foo, within my working directory [let's just say it's /] I make a folder named /src/ and inside is /src/FooClient.php. It contains:
<?php
namespace sammitch\foo;
class FooClient {}
While in / I run composer init and accept all of the defaults, because typing out the simple JSON config file that that generates is tedious. Now I have a composer.json that looks like:
{
"name": "Sammitch/foo",
"authors": [
{
"name": "Sammitch",
"email": "sammitch#sam.mitch"
}
],
"require": {}
}
All we need to do now is add a section to the end:
"autoload": {
"psr-4": {
"sammitch\\foo\\": "src/"
}
}
Now to make Composer do it's magic and make the autoloader just run composer dumpautoload. When this runs Composer will create the /vendor/ folder and the autoloader.
Now all we need to do is:
<?php
require('vendor/autoload.php');
use \sammitch\foo\Client as FooClient()
$c = new FooClient();
Now not only do you have a top-tier autoloader, but you're also set up to start using Composer packages and leveraging all that good stuff from Packagist.

Composer Autoload is not loading the Class

I am new to using composer and psr-0. I have tried a small app using composer and psr-0. I have used namespace to load a particular class. When i call a class using composer vendor/autoload I am getting class not found error.
My composer.json file:/var/www/html/silexapp/composer.json
{
"require": {
"silex/silex": "~2.0",
"symfony/console": "~2.6"
},
"autoload": {
"psr-0": {
"MyApp": "/silexapp/app"
}
}
}
My composer vendor autoload file: /var/www/html/silexapp/vendor/autoload.php
<?php
// autoload.php #generated by Composer
require_once __DIR__ . '/composer' . '/autoload_real.php';
return ComposerAutoloaderInitf7241d907c173a8d77da0791cc918856::getLoader();
My class file name Underline.php: /var/www/html/silexapp/app/Tnq/Todo/Command/Underline.php
<?php
namespace MyApp\Tnq\Todo\Command;
class Underline{
public function add($a,$b){
return $result = $a+$b;
}
}
?>
My another class file name Bold.php: /var/www/html/silexapp/app/Tnq/Todo/Command/Bold.php
<?php
require_once "../../../../vendor/autoload.php";
//require_once "Underline.php";
use MyApp\Tnq\Todo\Command as tool;
echo "this is the index file to check namespace.";
$c = new tool\Underline();
echo "=============================";
echo "Addition : ".$c->add(2,2);
?>
I am getting "class not found error" in my bold.php class file, when I use autoload file. But when I directly included the underline class file, I am getting the output. Why it is not working when I use autoload?
Can anyone help me to find the issue?
The "key" should be a directory under the path you put as "value", that should be relative to your working directory. To look at it in a simple way, the namespace should map the directory structure; you are missing a MyApp directory.
If in your composer.json have:
"autoload": {
"psr-0": {
"MyApp\\": "app/"
}
}
Then you need a MyApp directory under app/. Try this:
composer.json:
// /var/www/html/silexapp/composer.json
{
"require": {
"silex/silex": "~2.0",
"symfony/console": "~2.6"
},
"autoload": {
"psr-0": {
"Tnq\\": "app/"
}
}
}
Underline.php:
<?php
// /var/www/html/silexapp/app/Tnq/Todo/Command/Underline.php
namespace Tnq\Todo\Command;
class Underline
{
public function add($a,$b)
{
return $result = $a+$b;
}
}
Bold.php:
<?php
// /var/www/html/silexapp/app/Tnq/Todo/Command/Bold.php
require_once "../../../../vendor/autoload.php";
use Tnq\Todo\Command as tool;
echo 'this is the index file to check namespace.' . PHP_EOL;
$c = new tool\Underline();
echo "=============================";
echo "Addition : ".$c->add(2,2);
In theory, that should works (not tested :) )
sources:
https://getcomposer.org/doc/04-schema.md#psr-0
http://www.php-fig.org/psr/psr-0/

Php psr-4 Class not Found Error using Composer

I'm trying to exercise MVC concepts with php on "wamp-server"
At local directory i have the index.php page for basic routing with alto-router package and a routes.php file:
<?php
$router->map('GET','/test', 'Acme\Controllers\PageController#test' ,'test');
composer.json file is:
{
"name": "eren/eren",
"authors": [
{
"name": "Eren Ardahan",
"email": "???#???.com"
}
],
"require": {
"filp/whoops": "^1.1",
"altorouter/altorouter": "1.1.0"
},
"autoload":{
"psr-4":{"Acme\\":"src/"}
}
}
PageController.php is
<?php namespace Acme\Controllers;
use Acme\Testing\Test;
class PageController
{
public function test(){
include(__DIR__ . "/../../views/test.php");
//---Deleted lines
$test = new Test;
$test -> test();
/---
}
}
The Test.php in the acme directory is:
<?php namespace Acme\Testing;
class Test{
public function test(){
echo "Working";
}
}
And The test.php in the view directory is above.And it works when i deleted the commented two lines in PageController.php
<?php
echo "TEST PAGE <br>";
But with this lines there is an error :
Class 'Acme\Testing\Test' not found..
As i said in the comment the problem is that the namespace is not correct.
I created this answer for people who might find this question in the future.
You have a directory called source wich has the namespace Acme. When u add another directory inside the source folder called acme the namespace will be:
Acme\acme
You will have to change the acme folder to Testing to get the right namespace.

Categories