I'm having a problem with PHP autoload with a specific class, where it keeps saying it's not found.
Error:
Warning: require_once(Models/BaseModel.php): failed to open stream: No such file or directory in /var/www/html/icompare/init.php on line 29
Fatal error: require_once(): Failed opening required 'Models/BaseModel.php' (include_path='.:/usr/share/php:/var/www/html/icompare/lib') in /var/www/html/icompare/init.php on line 29
How my autoload is started in init.php:
set_include_path(get_include_path().PATH_SEPARATOR.APP_ROOT_PATH.DIRECTORY_SEPARATOR.'lib');
spl_autoload_extensions(".php");
spl_autoload_register(function($className){
$className = str_replace('\\', DIRECTORY_SEPARATOR, $className);
$file = $className.".php";
// echo 'Loading file: '.$file.PHP_EOL;
require_once $file;
});
My folder structure:
BaseModel class (it's not the full file):
<?php
/**
* Model Base CRUD Banco de Dados
*/
namespace Models;
class BaseModel {
protected $tableName = null;
public function find($value, $field = 'id', $fieldType = \PDO::PARAM_STR){
if(!isset($this->tableName) || empty($this->tableName)){
return null;
}
$DB = new \DB;
$sql = sprintf("SELECT * FROM %s WHERE %s = :value", $this->tableName, $field);
$stmt = $DB->prepare($sql);
$stmt->bindParam(':value', $value, $fieldType);
$stmt->execute();
Somehow PHP is looking for a "Models/" capitalized folder?
Have you guys ever experienced that before?
You're generating the filename from the classname by doing a string replace of backslash to slash:
$className = str_replace('\\', DIRECTORY_SEPARATOR, $className);
Since the classname you're trying to load is \Models\BaseModel, the filename that gets generated is .../Models/BaseModel.php. However, your file's actual name is .../models/BaseModel.php, so the require fails because unixy operating systems have case sensitive filenames. If you follow PSR-4 (which you should) then your namespaces should match your directories and your files should match your classes. Thus, the class \Models\BaseModel should be defined in a file named .../Models/BaseModel.php.
Related
Using spl_autoload_register() with a class that uses namespace, causes this error message: Fatal error: Uncaught Error: Class "MyClass" not found...
Before this error message, the autoloader does echo "...MyClass.php IS found".
Two files are used: "/index.php" (in the root directory) and "/classes/MyClass.php".
Index.php:
declare(strict_types=1);
define ('ROOT_DIR', __DIR__ . '/');
define ('CLASS_DIR', ROOT_DIR . 'classes/');
spl_autoload_register(function($class) {
$filepath = CLASS_DIR . str_replace('\\', DIRECTORY_SEPARATOR, $class) . '.php';
if (file_exists($filepath)) {
require_once $filepath;
echo('<br /><b>' . $filepath . '</b> IS found.<br />');
} else {
echo('<br /><b>' . $filepath . '</b> not found.<br />');
exit;
}
});
$myclass = new MyClass();
MyClass.php:
declare(strict_types=1);
namespace App\Classes
class MyClass
{
// ...
}
Does anyone know how to solve this?
According to https://www.php-fig.org/psr/psr-4/, a vendor name is required, so I am using "App" as a top-level namespace name, even though it is not a directory (because my website uses the root of the server).
I also tried adding "use App/classes/Myclass" to index.php before "$myclass = new MyClass()" but this causes even more problems, because the autoloader will look for the directory "/classes/App/Classes"...
With the namespace removed from the class, everything works fine, and I can use the functions of the class through $myclass. But I would like to start using namespaces... Any help would be really appreciated! <3
Conclusion: Either the line "$myclass = new App\Classes\MyClass();"
or "use App\Classes\MyClass;" should be used.
So it is not possible to use the root of the server while also having a
top-level namespace name ("App") with this autoload function. The
function has to be expanded to allow for this possibility. And the "classes" directory will be renamed to "Classes". I will post my solution when it is ready!
For more details, read the comments below the answer by #IMSoP (Thank
you very much for your help!)
Solution:
declare(strict_types=1);
namespace App;
define ('ROOT_DIR', $_SERVER['DOCUMENT_ROOT'] . '/');
define ('BASE_DIR', __DIR__ . '/');
define ('TOP_LEVEL_NAMESPACE_NAME', __NAMESPACE__ . '/');
spl_autoload_register(function($class) {
if (BASE_DIR == ROOT_DIR . TOP_LEVEL_NAMESPACE_NAME) {
$filepath = ROOT_DIR . str_replace('\\', DIRECTORY_SEPARATOR, $class) . '.php';
} else {
$filepath = BASE_DIR . str_replace('\\', DIRECTORY_SEPARATOR, $class) . '.php';
$filepath = str_replace(TOP_LEVEL_NAMESPACE_NAME, '', $filepath);
}
if (file_exists($filepath)) {
require_once $filepath;
} else {
echo('Class <b>' . end(explode('\\', $class)) . '.php</b> was not found.');
exit;
}
});
use App\Classes\MyClass;
$myclass = new MyClass();
This solution works whether the application is in the directory with the same name as the top-level namespace name, or anywhere else!
You might want to read through the manual pages on autoloading and namespaces to make sure you understand the key concepts.
You have declared a class called MyClass inside the namespace App\Classes; that means that its fully qualified name is App\Classes\MyClass - that's the name you need to call it by from outside that namespace. There could simultaneously be a different class whose fully-qualified name was just MyClass, because it wasn't in any namespace, and any number of others in other namespaces, like App\Security\MyClass, App\UI\MyClass, etc.
Then you've attempted to reference a class in index.php called MyClass, which triggers the autoloader. The autoloader translates it to a path like .../classes/MyClass.php, and loads the right file; but that file defines your namespaced class. So after the autoloader has finished, there is no class called MyClass, only App\Classes\MyClass and the code fails.
If instead you write new App\Classes\MyClass, you'll get the opposite problem: the string passed to your autoloader is 'App\Classes\MyClass' and you translate that to a file path like '.../classes/App/Classes/MyClass.php' - but that's not where your file is. (Adding use App\ClassesMyClass does the same thing - use statements are just compiler assistance to avoid writing out the fully-qualified name as often.)
What you need to do is both:
Consistently use fully-qualified class names (or alias them with use)
Lay out your files to match your namespace structure, so that your autoloader can find them, which generally means a directory per namespace
I read on SO and experiment with some answers but my code does not work:
I have two classes: C:\Apache24\htdocs\phpdb\classes\dbconnection\mysqlconnection\MySqlConnection.php
and C:\Apache24\htdocs\phpdb\classes\utilities\mysqlutilities\CreateTableDemo.php.
In CreateTableDemo I have the following code:
namespace utilities\mysqlutilities;
use dbconnection\mysqlconnection\MySqlConnection as MSC;
spl_autoload_register(function($class){
$class = 'classes\\'.$class.'.php';
require_once "$class";
});
I get the following warning:
`Warning: require_once(classes\dbconnection\mysqlconnection\MySqlConnection.php): failed to open stream: No such file or directory in C:\Apache24\htdocs\phpdb\classes\utilities\mysqlutilities\CreateTableDemo.php on line 10`.
I understand the warning, the script does not find the namespaced class in the same folder, so I changed the spl_autoload_register to look for a relative path: __DIR__."\\..\\..\\classes\\.$class.'.php'. I get the
warning: `Warning: require_once(C:\Apache24\htdocs\phpdb\classes\utilities\mysqlutilities\..\..\classes\dbconnection\mysqlconnection\MySqlConnection.php): failed to open stream: No such file or directory in C:\Apache24\htdocs\phpdb\classes\utilities\mysqlutilities\CreateTableDemo.php on line 10`.
I cannot find a way to direct the script to the namespaced class.
Thanks in advance for any help.
Create a autoloader-class in a separate file:
class Autoloader {
static public function loader($path) {
$filename = __DIR__.'/classes/'.str_replace("\\", '/', $path).".php";
if (file_exists($filename)) {
include($filename);
$aClass = explode('\\', $path);
$className = array_pop($aClass);
if (class_exists($className)) {
return TRUE;
}
}
return FALSE;
}
}
spl_autoload_register('Autoloader::loader');
And include it in you index file (or whatever).
It will load all your namespaced classes located in folder "classes".
require_once '/PATH_TO/autoload.php';
BTW: the trick is to replace the backslashes to regular slashes.
Works fine for me.
EDIT: Place the autoloader.php at same level like your "classes" folder is. :-)
It's failing because the path to the class is wrong relative to where you are requiring from. Try:
namespace utilities\mysqlutilities;
use dbconnection\mysqlconnection\MySqlConnection as MSC;
spl_autoload_register(function($class){
$exp = explode('classes', __DIR__);
$base = reset($exp);
$class = $base."classes".DIRECTORY_SEPARATOR.$class.".php";
require_once $class;
});
This question already has answers here:
How do I use PHP namespaces with autoload?
(13 answers)
Closed 6 years ago.
I am trying to understand how to define a working autoloader for a trivial application with namespaces.
I created following structure:
public
index.php
src
Models
WordGenerator.php
Obviously, later it will grow. The WordGenerator.php file is following:
<?php
namespace Models;
class WordGenerator {
public $filename;
public function __construct($filename) {
$this->_filename = $filename;
}
}
Now I try to create instance of this object in index.php:
<?php
use \Models;
$wg = new WordGenerator("words.english");
Obviously I get fatal error because I did not define autoloader. However though, according to documentation all I can pass is $classname. How should I define the autoloader function to take namespace declared by use statement then??
[edit]
I was wrong understood a moment ago. So here's my code for index.php:
spl_autoload_register(function ($className) {
$className = ltrim($className, '\\');
$prepend = "..\\src\\";
$fileName = "{$prepend}";
$namespace = '';
if ($lastNsPos = strrpos($className, '\\')) {
$namespace = substr($className, 0, $lastNsPos);
$className = substr($className, $lastNsPos + 1);
$fileName = $prepend.str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
}
$fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
require $fileName;
});
//require '../src/Models/WordGenerator.php';
use Models;
$wg = new WordGenerator("words.english");
echo $wg->getRandomWord();
Now, this does not work and I get:
Warning: The use statement with non-compound name 'Models' has no effect in C:\xampp\htdocs\Hangman\public\index.php on line 22
Warning: require(..\src\WordGenerator.php): failed to open stream: No such file or directory in C:\xampp\htdocs\Hangman\public\index.php on line 16
Fatal error: require(): Failed opening required '..\src\WordGenerator.php' (include_path='.;C:\xampp\php\PEAR') in C:\xampp\htdocs\Hangman\public\index.php on line 16
However when I change new WordGenerator to new \Models\WordGenerator it works. Now, the question is: how can I pass namespaces declared by use statement to autoloader function to make it work properly?
Your use statement is incorrect. You want use Models\WordGenerator;
The use operator doesn't declare anything but an alias. Consider the expanded form:
use Models\WordGenerator as WordGenerator;
Which is equivalent.
You can alias a namespace rather than a class, but it doesn't work in the way you're attempting. For example:
use Models as Foo;
$wg = new Foo\WordGenerator("words.english");
Would work. However:
use Models;
Is equivalent to:
use Models as Models;
Which effectively does nothing.
For more information see Using namespaces: Aliasing/Importing in the PHP manual.
Please look at documentation. Autoloader must be defined by you at beginning of you script. At provided link there is example autoloader and more complex solution
How can I check if a class exists already in a folder then do not load this class again from another folder?
I have this folder structure for instance,
index.php
code/
local/
And I have these two identical classes in code/ and local/
from local/
class Article
{
public function getArticle()
{
echo 'class from local';
}
}
from core,
class Article
{
public function getArticle()
{
echo 'class from core';
}
}
So I need a script that can detects the class of Article in local/ - if it exits already in that folder than don't load the class again from core/ folder. Is it possible?
This is my autoload function in index.php for loading classes,
define ('WEBSITE_DOCROOT', str_replace('\\', '/', dirname(__FILE__)).'/');
function autoloadMultipleDirectory($class_name)
{
// List all the class directories in the array.
$main_directories = array(
'core/',
'local/'
);
// Set other vars and arrays.
$sub_directories = array();
// When you use namespace in a class, you get something like this when you auto load that class \foo\tidy.
// So use explode to split the string and then get the last item in the exloded array.
$parts = explode('\\', $class_name);
// Set the class file name.
$file_name = end($parts).'.php';
// List any sub dirs in the main dirs above and store them in an array.
foreach($main_directories as $path_directory)
{
$iterator = new RecursiveIteratorIterator
(
new RecursiveDirectoryIterator(WEBSITE_DOCROOT.$path_directory), // Must use absolute path to get the files when ajax is used.
RecursiveIteratorIterator::SELF_FIRST
);
foreach ($iterator as $fileObject)
{
if ($fileObject->isDir())
{
// Replace any backslash to '/'.
$pathnameReplace = str_replace('\\', '/', $fileObject->getPathname());
//print_r($pathnameReplace);
// Explode the folder path.
$array = explode("/",$pathnameReplace);
// Get the actual folder.
$folder = end($array);
//print_r($folder);
// Stop proccessing if the folder is a dot or double dots.
if($folder === '.' || $folder === '..') {continue;}
//var_dump($fileObject->getPathname());
// Must trim off the WEBSITE_DOCROOT.
$sub_directories[] = preg_replace('~.*?(?=core|local)~i', '', str_replace('\\', '/', $fileObject->getPathname())) .'/';
}
}
}
// Mearge the main dirs with any sub dirs in them.
$merged_directories = array_merge($main_directories,$sub_directories);
// Loop the merge array and include the classes in them.
foreach($merged_directories as $path_directory)
{
if(file_exists(WEBSITE_DOCROOT.$path_directory.$file_name))
{
// There is no need to use include/require_once. Autoload is a fallback when the system can't find the class you are instantiating.
// If you've already included it once via an autoload then the system knows about it and won't run your autoload method again anyway.
// So, just use the regular include/require - they are faster.
include WEBSITE_DOCROOT.$path_directory.$file_name;
}
}
}
// Register all the classes.
spl_autoload_register('autoloadMultipleDirectory');
$article = new Article();
echo $article->getArticle();
of course I get this error,
Fatal error: Cannot redeclare class Article in C:\wamp\...\local\Article.php on line 3
class_exists seems to be the answer I should look into, but how can I use it with the function above, especially with spl_autoload_register. Or if you have any better ideas?
Okay, I misunderstood your question. This should do the trick.
<?php
function __autoload($class_name) {
static $core = WEBSITE_DOCROOT . DIRECTORY_SEPARATOR . "core";
static $local = WEBSITE_DOCROOT . DIRECTORY_SEPARATOR . "local";
$file_name = strtr($class_name, "\\", DIRECTORY_SEPARATOR):
$file_local = "{$local}{$file_name}.php";
require is_file($file_local) ? $file_local : "{$core}{$file_name}.php";
}
This is easily solved by using namespaces.
Your core file goes to /Core/Article.php:
namespace Core;
class Article {}
Your local file goes to /Local/Article.php:
namespace Local;
class Article {}
And then use a very simple autoloader, e.g.:
function __autoload($class_name) {
$file_name = strtr($class_name, "\\", DIRECTORY_SEPARATOR);
require "/var/www{$file_name}.php";
}
PHP loads your classes on demand, there's no need to load the files up front!
If you want to use an article simply do:
<?php
$coreArticle = new \Core\Article();
$localArticle = new \Local\Article();
I am fiddling around with autoloading, and trying to make a file structure that abides to the PSR-0 Standard. However I am getting this error:
Warning: require(GetMatchHistory\api.php): failed to open stream: No such file or directory in C:\xampp\htdocs\Test\Test.php on line 15
Fatal error: require(): Failed opening required 'GetMatchHistory\api.php' (include_path='.;C:\xampp\php\PEAR') in C:\xampp\htdocs\Test\Test.php on line 15
And here is my file structure:
I am using Test PHP with this autoloader function:
function autoload($className)
{
$className = ltrim($className, '\\');
$fileName = '';
$namespace = '';
if ($lastNsPos = strrpos($className, '\\')) {
$namespace = substr($className, 0, $lastNsPos);
$className = substr($className, $lastNsPos + 1);
$fileName = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
}
$fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
require $fileName;
}
spl_autoload_register('autoload');
$Query = new GetMatchHistory_api();
This function is copy-pasted from the suggested PSR-0 function here
Am I misunderstanding with regards to how the structure should be? The class within "api.php" is GetMatchHistory_api
Edit: Another problem
I have used the suggested answer by MrCode, however now I am having an issue where the autoloader wont load a class that is in another directory.
use Classes\Queries\History\GetMatchHistoryAPI;
use Classes\Queries\History\GetMatchHistoryBASE;
use Classes\Utilities\send;
When I am calling the send class, from within a function inside GetMatchHistoryAPI, I am receiving the error:
Warning: require(Classes\Queries\History\send.php): failed to open stream: No such file or directory in C:\xampp\htdocs\Test\Test.php on line 15
However, as you can tell from the above image, the send class is not in that file path. Why is this error occurring?
Based on that structure, you would need to rename the class to Classes_Queries_GetMatchHistory_api and change the code that instantiates it to:
$Query = new Classes_Queries_GetMatchHistory_api();
The reason for this is your Test.php resides at the root and the api class is in the directory Classes/Queries/GetMatchHistory.
Example using namespaces instead of the underscore method:
api.php:
namespace Classes\Queries\GetMatchHistory;
class api
{
}
Test.php:
spl_autoload_register('autoload');
$Query = new Classes\Queries\GetMatchHistory\api();
Or using use:
use Classes\Queries\GetMatchHistory\api;
spl_autoload_register('autoload');
$Query = new api();
To address your comment:
I was going to have the same class names, but under a different folder (so GetMatchHistory - api.php and GetMatchDetails - api.php). I guess this would make it too ambiguous when calling the classes however
Namespaces are designed to solve this very problem. Namespaces allow you to have classes with the same name (but in different namespaces) and avoid any conflicts.
As an example, you have an api class under both GetMatchHistory and GetMatchDetails.
File: Classes/Queries/GetMatchHistory/api.php
namespace Classes\Queries\GetMatchHistory;
class api
{
public function __construct(){
echo 'this is the GetMatchHistory api';
}
}
File: Classes/Queries/GetMatchDetails/api.php
namespace Classes\Queries\GetMatchDetails;
class api
{
public function __construct(){
echo 'this is the GetMatchDetails api, I am separate to the other!';
}
}
File: Test.php (usage example)
spl_autoload_register('autoload');
$historyApi = new Classes\Queries\GetMatchHistory\api();
$detailsApi = new Classes\Queries\GetMatchDetails\api();
If you like, you can give an alias instead of typing out the whole fully qualified namespace:
use Classes\Queries\GetMatchHistory\api as HistoryApi;
use Classes\Queries\GetMatchDetails\api as DetailsApi;
$historyApi = new HistoryApi();
$detailsApi = new DetailsApi();
As you can see, namespaces make it possible to have multiple different classes with the same name, without having conflicts or making it ambiguous.