I have strange problem with autoload function.
my structure is like this
Project
|
+-- test.php
|
+-- class
| |
| +-- class.news.php
I have this code:
function __autoload($class_name) {
if(file_exists('class/class.'.strtolower($class_name).'.php')){
require_once('class/class.'.strtolower($class_name).'.php');
} else {
throw new Exception("Unable to load $class_name.");
}
}
try {
$a = new News();
} catch (Exception $e) {
echo $e->getMessage(), "\n";
}
i got
Fatal error: Class 'News' not found
file class.news.php
class News{
function insert($request){
return "ok";
}
}
im running this on wamp server on windows 10
Use document root to avoid issues with relative paths:
$prefix = $_SERVER['DOCUMENT_ROOT'] . '/class/class.';
$filename = $prefix . strtolower($class_name) . '.php';
if(file_exists($prefix)){
require_once($prefix);
}
Related
I run that script manually and everything works,
$container = require '../config/bootstrap.php';
try {
$test = $container->get(Test::class);
$test->run();
}
catch(\Exception $e) {
echo $e->getMessage() . "\n";
die;
}
but when I call that file from another folder like the following :
$script = __DIR__ .'/folder/test-service.php';
$output = shell_exec('php '.$script);
var_dump($output);
I get the following error:
Fatal error: require(): Failed opening required '../config/bootstrap.php' (include_path='.:') in /anotherFolder/folder/test-service.php on line 13
and also after that, I got a lot of error that files do not exist.
bootstrap.php include the class mapping of PHP-DI
require '../vendor/autoload.php';
use DI\ContainerBuilder;
$containerBuilder = new ContainerBuilder;
$containerBuilder->addDefinitions(__DIR__ . '/config.php');
$container = $containerBuilder->build();
return $container;
The require instruction is relative to your current directory.
You could replace the line with require __DIR__.'/../config/bootstrap.php';
I started with PHRoute today and I have problem with loading classes.
I have following directory structure:
/
public
index.php
app
controllers
Home.php
models
views
I want make routes in index.php
use Phroute\Phroute\RouteCollector;
use Phroute\Phroute\Dispatcher;
// Autoloader for Composer
if (file_exists(ROOT . 'vendor/autoload.php')) {
require ROOT . 'vendor/autoload.php';
}
// load application config (error reporting etc.)
require APP . 'config/config.php';
function _autoload($class)
{
$path = APP . "controllers/" . $class . ".php";
if(file_exists(stream_resolve_include_path($path)))
require($path);
}
spl_autoload_register("_autoload");
$router = new RouteCollector();
$router->any('/', ['Home','displayUser']);
$dispatcher = new Dispatcher($router->getData());
try {
$response = $dispatcher->dispatch($_SERVER['REQUEST_METHOD'], parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
} catch (Exception $e) {
echo $e->getMessage();
die();
}
echo $response;
Home.php looks like:
class Home {
public function displayUser()
{
return 'This is the default page and will respond to /controller and /controller/index';
}
}
I am still getting error "Uncaught Error: Class 'Home' not found...". Where I made mistake?
I have a php file called index which is the entry point for my api with the following code
//Entry point...
try {
echo (new requestHandler($_REQUEST['request'], $_SERVER['HTTP_ORIGIN']))->DoStuff();
} catch (Exception $e) {
echo json_encode(Array('error' => $e->getMessage()));
}
Then the requestHandler.php handles the request
public function __construct($request)
{
echo "constructor";
//do some things
}
However when i call index.php it seems to give an error
PHP Fatal error: Class 'requestHandler' not found in .../index.php
Note: both are separate files...
In this particular case, I suggest you simply add this to the top of your index script...
require_once __DIR__ . '/requestHandler.php';
This is of course assuming the requestHandler class is defined in a file named requestHandler.php.
If you want to try using an autoloader, you need to stick to a convention of class to file names. In your case, it seems like this should suffice (again, in your index script)...
spl_autoload_register(function($class) {
$path = sprintf('%s/%s.php', __DIR__, $class);
if (is_readable($path)) {
require $path;
}
});
I have a issue, i have the following interface (http://pastebin.com/c11xbdxh)
and i have the following class which implements the interface above (http://pastebin.com/m1zGNfSm).
I am using the following autoload function in order to load the classes dynamically:
function autoloadClass($className)
{
$classParts = explode("\\", $className);
$fileName = SYSTEM_CORE_PATH . DIRECTORY_SEPARATOR . "classes" . DIRECTORY_SEPARATOR . strtolower(str_replace('_', DIRECTORY_SEPARATOR, end($classParts)) . '.class.php');
if (is_readable($fileName)) {
if (SYSTEM_DEBUG) {
include_once($fileName);
} else {
#include_once($fileName);
}
}
}
spl_autoload_register("autoloadClass");
and when i creating a new object class (under the autoloading code) i don't get any error neither any output...
try {
$db = new Core\Infrastructure\MySQL(array('user' => DB_USER, 'pass' => DB_PASS, 'host' => DB_HOST, 'name' => DB_NAME));
} catch (PDOException $pdoE) {
echo $pdoE->getMessage();
} catch (Exception $e) {
echo $e->getMessage();
}
echo "<pre>ddd";
$db->runQuery("SELECT * FROM `users`;");
print_r( $db->fetchData());
Thanks for your kind help :)
"Don't get any error neither any output" usually means a Fatal or Parse error eaten by error_reporting settings. Check logs. Make sure error_reporting(E_ALL) is set, preferrably in ini file.
Add debug output when $fileName is not readable. This will likely provide an insight.
Ok i've fixed it, the autoloading only loads the class from the file, it does'nt load the interface.
i've simply added a short code based on class_implements function to the autoload function i wrote.
thanks for all of your help :D
I'm trying to register a few autoloaders and I get an HTTP 500. My error log says the following:
[05-Aug-2013 04:32:38 UTC] PHP Fatal error: Uncaught exception
'LogicException' with message 'Function 'Autoloader::config' not
callable (non-static method Autoloader::config() should not be called
statically)' in /home2/canforce/public_html/index.php:5
There was some stack trace part on the end of the error log, but it came showed up in huge letters so I took it out, I didn't think it was important.
I think my autoloader should work based on what I've read but for some reason it doesn't, here's the code:
index.php
include("config/autoloader.php");
spl_autoload_register('Autoloader::config');
spl_autoload_register('Autoloader::controller');
spl_autoload_register('Autoloader::service');
config/autoloader.php
class Autoloader {
function config($class) {
$file = 'config/' . $class . '.php';
if(file_exists($file)) {
require_once $file;
}
}
function controller($class) {
$file = 'presentation/controllers/' . $class . '.php';
if(file_exists($file)) {
require_once $file;
}
}
function service($class) {
$file = 'model/services/' . $class . '.php';
if(file_exists($file)) {
require_once $file;
}
}
}
You need to create an instance of the Autoloader class and then pass it to the register function.
include("config/autoloader.php");
$autoloader = new Autoloader();
spl_autoload_register(array($autoloader, 'loader'));