What's wrong with my autoloader? - php

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'));

Related

run script in background(shell_exec) fails on composer/PHP-DI function

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';

PHRoute class not found when routing

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?

ZF2 Uncaught Error:Class 'ArrayUtils' not found in E:\Temp\htdocs\zf-tutorial\public\index.php:43

I am new at Zend2 and i am following the Album tuturial on Zend. I get the following error:
Fatal error: Uncaught Error: Class 'ArrayUtils' not found in E:\Temp\htdocs\zf-tutorial\public\index.php:43 Stack trace: #0 {main} thrown in E:\Temp\htdocs\zf-tutorial\public\index.php on line 43
I can't find whats the problem, what do i do wrong? Do i miss some code? Or do i miss some rules in the tutorial?
here is my index.php file
<?php
use Zend\Mvc\Application;
/**
* Display all errors when APPLICATION_ENV is development.
*/
if ($_SERVER['APPLICATION_ENV'] === 'development') {
error_reporting(E_ALL);
ini_set("display_errors", 1);
}
/**
* This makes our life easier when dealing with paths. Everything is relative
* to the application root now.
*/
chdir(dirname(__DIR__));
// Decline static file requests back to the PHP built-in webserver
if (php_sapi_name() === 'cli-server') {
$path = realpath(__DIR__ . parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
if (__FILE__ !== $path && is_file($path)) {
return false;
}
unset($path);
}
// Composer autoloading
include __DIR__ . '/../vendor/autoload.php';
if (! class_exists(Application::class)) {
throw new RuntimeException(
"Unable to load application.\n"
. "- Type `composer install` if you are developing locally.\n"
. "- Type `vagrant ssh -c 'composer install'` if you are using Vagrant.\n"
. "- Type `docker-compose run zf composer install` if you are using Docker.\n"
);
}
// Retrieve configuration
$appConfig = require __DIR__ . '/../config/application.config.php';
if (file_exists(__DIR__ . '/../config/development.config.php')) {
$appConfig = ArrayUtils::merge($appConfig, require __DIR__ . '/../config/development.config.php');
}
// Run the application!
Application::init($appConfig)->run();
To be able to use the Zend\Stdlib\ArrayUtils class, you have to either:
add a use statement at the top of your file: use Zend\Stdlib\ArrayUtils; or
change your ArrayUtils invocation to Zend\Stdlib\ArrayUtils

autoloader for loading classes won't work as expected

recently i started working with OOP and i created a classLoader to load the classes i use.. so i made this class and worked with it ( local ) and all went fine. But when i uploaded everything to my webhost it stopped working. i get the following error when i visit a page where the loader needs to load a class..
Fatal error: Uncaught exception 'Exception' with message 'Class "formhandler" could not be autoloaded from:
/var/www/vhosts/***.nl/httpdocs/admin/lib/formhandler.php' in
/var/www/vhosts/***.nl/httpdocs/admin/index.php:30 Stack trace:
#0 /var/www/vhosts/***.nl/httpdocs/admin/index.php(109): __autoload('formhandler')
#1 {main} thrown in /var/www/vhosts/***.nl/httpdocs/admin/index.php on line 30
the code for my autoloader is as followed..
function __autoload($className)
{
// get the base dir.
$base = dirname(__FILE__);
// get path
$path = $className;
$file = $base . "/lib/" . $path . '.php';
//if exists get file else throw error
if (file_exists($file))
{
require $file;
}
else
{
error_log('Class "' . $className . '" could not be autoloaded');
throw new Exception('Class "' . $className . '" could not be autoloaded from: ' . $file);
}
}
Compare the production path of the formhandler class. I guarantee there will be a difference between it and /var/www/vhosts/.nl/httpdocs/admin/lib/formhandler.php. Correct it.
i found the solution. i had new formhandler(); but instead i had to use new FormHandler(); in my script because my webhost didn;t find it.. verry annoying but it works now!

php: autoload exception handling

I'm extending my previous question (Handling exceptions within exception handle) to address my bad coding practice.
I'm trying to delegate autoload errors to a exception handler.
<?php
function __autoload($class_name) {
$file = $class_name.'.php';
try {
if (file_exists($file)) {
include $file;
}else{
throw new loadException("File $file is missing");
}
if(!class_exists($class_name,false)){
throw new loadException("Class $class_name missing in $file");
}
}catch(loadException $e){
header("HTTP/1.0 500 Internal Server Error");
$e->loadErrorPage('500');
exit;
}
return true;
}
class loadException extends Exception {
public function __toString()
{
return get_class($this) . " in {$this->file}({$this->line})".PHP_EOL
."'{$this->message}'".PHP_EOL
. "{$this->getTraceAsString()}";
}
public function loadErrorPage($code){
try {
$page = new pageClass();
echo $page->showPage($code);
}catch(Exception $e){
echo 'fatal error: ', $code;
}
}
}
$test = new testClass();
?>
the above script is supposed to load a 404 page if the testClass.php file is missing, and it works fine, UNLESS the pageClass.php file is missing as well, in which case I see a
"Fatal error: Class 'pageClass' not found in D:\xampp\htdocs\Test\PHP\errorhandle\index.php on line 29" instead of the "fatal error: 500" message
I do not want to add a try/catch block to each and every class autoload (object creation), so i tried this.
What is the proper way of handling this?
Have you tried checking for pageClass early on in the process, since it seems to be necessary even to get the error page out? If it doesn't exist, and if you don't want to write the 404 page w/o any objects (e.g. just HTML), bombing out of execution where that class doesn't exist would seem to be a good path.
Hope that helps.
Thanks,
Joe

Categories