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?
Related
Yii2 shows
SQLSTATE[HY000] [2002] A socket operation was attempted to an unreachable host.
when there is no internet access, how can I make it redirect to a page, says ./index.php?r=site/neterror? I tried to do this in web/index.php by using this code
<?php
use yii\db\Exception;
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');
require(__DIR__ . '/../vendor/autoload.php');
require(__DIR__ . '/../vendor/yiisoft/yii2/Yii.php');
$config = require(__DIR__ . '/../config/web.php');
try
{
(new yii\web\Application($config))->run();
}
catch(Exception $e) {
header("Location: ./index.php?r=site/error"); /* Redirect browser */
exit();
}
but all I get back is The page isn't redirecting properly.
Following Database Exception View With different msg shown only when YII_DEBUG is true in Entry Script..
As Defined in Yii ErrorHandler Class to use Own View On UserException you have to false YII_DEBUG
class ErrorHandler extends \yii\base\ErrorHandler{
....
protected function renderException($exception){
..
$useErrorView = $response->format === Response::FORMAT_HTML && (!YII_DEBUG || $exception instanceof UserException);
if ($useErrorView && $this->errorAction !== null) {
$result = Yii::$app->runAction($this->errorAction);
if ($result instanceof Response) {
$response = $result;
} else {
$response->data = $result;
}
}
}
}
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);
}
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'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'));
How can this be done? I'm trying to do this for about half an hour and it's getting pretty annoying. You would this this should be an basic and easy thing to setup for a framework like this. I hope maybe there's an easy way i missed, because i'm starting to thing i should not chose this framework at all if such basic tings are so hard to setup.
This is in my bootstrap.php file that should do the trick.
if ( ! defined('SUPPRESS_REQUEST'))
{
/**
* Execute the main request. A source of the URI can be passed, eg: $_SERVER['PATH_INFO'].
* If no source is specified, the URI will be automatically detected.
*/
$request = Request::instance();
try
{
// Attempt to execute the response
$request->execute();
}
catch (Exception $e)
{
if (Kohana::$environment === Kohana::DEVELOPMENT)
{
// Just re-throw the exception
throw $e;
}
echo "ok";
// Create a 404 response
$request->status = 404;
$view = View::factory('error404');
$request->response = $view->render();
}
echo $request->send_headers()->response;
}
But i'm still getting
Fatal error: Uncaught Kohana_Request_Exception [ 0 ]: Unable to find a route to match the URI: test ~ SYSPATH\classes\kohana\request.php [ 674 ] thrown in C:\Xampp\htdocs\system\classes\kohana\request.php on line 674
instead of my custom 404 page.
And yes, Kohana::$environment is set to Kohana::PRODUCTION;
It doesn't even get to the echo "ok"; part. Why doesn't the exception get caught?
Replace the last line of bootstrap.php with:
/**
* Set the production status
*/
define('IN_PRODUCTION', FALSE);
/**
* Execute the main request. A source of the URI can be passed, eg: $_SERVER['PATH_INFO'].
* If no source is specified, the URI will be automatically detected.
*/
$request = Request::instance();
try
{
$request->execute();
}
catch (Kohana_Exception404 $e)
{
$request = Request::factory('error/404')->execute();
}
catch (Kohana_Exception403 $e)
{
$request = Request::factory('error/403')->execute();
}
catch (ReflectionException $e)
{
$request = Request::factory('error/404')->execute();
}
catch (Kohana_Request_Exception $e)
{
$request = Request::factory('error/404')->execute();
}
catch (Exception $e)
{
if ( ! IN_PRODUCTION )
{
throw $e;
}
$request = Request::factory('error/500')->execute();
}
echo $request->send_headers()->response;
Create new controller "error.php":
<?php defined('SYSPATH') or die('No direct script access.');
class Controller_Error extends Controller {
public function action_404()
{
$this->request->status = 404;
$this->request->headers['HTTP/1.1'] = '404';
$this->request->response = 'error 404';
}
public function action_403()
{
$this->request->status = 403;
$this->request->headers['HTTP/1.1'] = '403';
$this->request->response = 'error 403';
}
public function action_500()
{
$this->request->status = 500;
$this->request->headers['HTTP/1.1'] = '500';
$this->request->response = 'error 500';
}
} // End Error
Create two files (exception404.php и exception403.php) in "kohana" folder:
<?php defined('SYSPATH') or die('No direct access');
class Kohana_Exception403 extends Kohana_Exception {
public function __construct($message = 'error 403', array $variables = NULL, $code = 0)
{
parent::__construct($message, $variables, $code);
}
} // End Kohana_Exception 403
<?php defined('SYSPATH') or die('No direct access');
class Kohana_Exception404 extends Kohana_Exception {
public function __construct($message = 'error 404', array $variables = NULL, $code = 0)
{
parent::__construct($message, $variables, $code);
}
} // End Kohana_Exception 404
Now you can manually throw 404 and 403 errors (you can't throw error 500 ;)
throw new Kohana_Exception404;
throw new Kohana_Exception403;
All you need to do is set the path to a different view in your bootstrap.php add:
Kohana_Exception::$error_view = 'error/myErrorPage';
that will parse all the variables currently being parsed to the error page that lives in:
system/views/kohana/error.php
ie:
<h1>Oops [ <?= $code ?> ]</h1>
<span class="message"><?= html::chars($message) ?></span>
Since v3.1 the Kohana guide incldues a tutorial on custom error pages which show a much cleaner way of solving this question.