Creating a new instance of another file - php

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

Related

Implementing Interface and Autoloading Classes

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

How to catch an exception from another class method PHP

I'm having trouble catching an exception in PHP
Here's my code.
try {
require $this->get_file_name($action);
}
catch (Exception $e) {
//do something//
}
and the method being called
private function get_file_name($action) {
$file = '../private/actions/actions_'.$this->group.'.php';
if (file_exists($file) === false) {
throw new Exception('The file for this '.$action.' was not found.');
}
else {
return $file;
}
}
Resulting in:
Fatal error: Uncaught exception 'Exception' with message $action was not found.'
Exception: The file for this $action was not found.
However If I put a try-catch block inside of the function and call the function, I'm able to catch the exception no problem.
What am I doing wrong?
If you are catching the Exception inside a namespace, make sure that you fall back to the global namespace:
...
}(catch \Exception $e) {
...
}...
You can also have a look at the following resources:
Why isn't my Exception being caught by catch?
http://php.net/manual/en/language.exceptions.php, top note by user zmunoz
I can't see all of the class body but If You want to use method out of the class it should be Public not Private.
Try to check if file You trying to get exists:
var_dump($file = '../private/actions/actions_'.$this->group.'.php');
IMO there is no file in this path

php Exception By getting a class that might exists

i try to make a function that load classes that are in the array. but it can be the case that the class don't exists, in that case i want to get an error string that an be places on that place and if it exists than the class has to be on that place.
so i thought i going to use try,catch to catch the error, but i stell get tge error.
try {
$content = $extension::content();
} catch (Exception $e) {
$content = '[undefined extension:'.$extension.']';
}
who can help me out
thanks
try using class_exists() documentation here
e.g
<?php
if( class_exists( $extension ) )
{
$content = $extension::content();
}else{
$content = '[undefined extension:'.$extension.']';
}
if ( class_exists($extension) && property_exists($extension, 'content') ) {
$content = $extension::content();
}else{
$content = '[undefined extension:'.$extension.']';
}
Since PHP5 you can autoload classes. As soon as you try to load a class that PHP does not know about it will run your custom function which will then be able to locate the class or throw an Exception of its non-existence.
Read about it here:
http://php.net/manual/en/language.oop5.autoload.php
In PHP, by default errors aren't exception and can't be catched. However, you can use set_exception_handler to throw an exception when a error occurs. Sadly, fatal error cannot be handled with this method.
To check if a class exists, you can call class_exists.

phpUnit - mock php extended exception object

I'm testing some legacy code that extends the default php exception object. This code prints out a custom HTML error message.
I would like to mock this exception object in such a way that when the tested code generates an exception it will just echo the basic message instead of giving me the whole HTML message.
I cannot figure out a way to do this. It seems like you can test for explicit exceptions, but you can't change in a general way the behavior of an exception, and you also can't mock up an object that extends a default php functionality. ( can't think of another example of this beyond exceptions... but it would seem to be the case )
I guess the problem is, where would you attach the mocked object?? It seems like you can't interfere with 'throw new' and this is the place that the object method is called....
Or if you could somehow use the existing phpunit exception functionality to change the exception behavior the way you want, in a general way for all your code... but this seems like it would be hacky and bad....
EDIT: here is some code to make things clearer:
class FooTest extends PHPUnit_Framework_TestCase{
public function testBar(){
include '/path/to/file.php'; //generates exception
$this->assertTrue($baz);
}
}
...
//overridden exception class
class Foo_Exception extends ErrorException{
...
so, my question, is there a way to deal with this overriden class, without doing it on a case by case basis? what if I'm not testing the behavior of the exception, just the code that causes the exception?
I would first write a test that captures the exception generation behavior:
include '/path/to/file.php'; //generates exception
public function testCatchFooException() {
try {
$this->assertTrue($baz);
}
catch (Exception $expected) {
$this->assertEquals('This is expected html from exception', $expected->getMessage());
return;
}
$this->fail('An expected Exception has not been raised Foo_Excpetion.');
}
Now you can do several things with this coverage test. You can either fix up the exception, or fix the code that causes the exception.
Another thing you can do is wrap the entire file.php in a class:
class FooClass {
function runFoo() {
include '/path/to/file.php'; //generates exception
}
}
Then add tests while using extract method until you isolate exception.
[EDIT]
Here is some serious procedural legacy code:
<?php
require_once 'helper.php'; //helper file
function countNewMessages($user_id) {
}
function countNewOrders() {
}
function countNewReturns() {
}
function getDB($init = NULL) {
}
function getDisplay() {
}
getDisplay();
?>
And here is the wrapped class:
<?php
require_once ''; //helper file
class Displayer {
function countNewMessages($user_id) {
}
function countNewOrders() {
}
function countNewReturns() {
}
function getDB($init = NULL) {
}
function getDisplay() {
}
}
?>
And now I can test it:
function testGetDisplay() {
$display = new Displayer();
$this->assertEquals('html code', $display->getDisplay());
}
And test the individual functions in it. And if I can further sprout methods on it.
The above test would be considered a coverage test. There may be bugs in it, but that is what it does. So as I sprout methods the get more code coverage from tests by sprouting that I can make sure I don't break the output.
The extened PHP exception object "prints" a costum HTML error page? You mean its error message is an entire HTML page? That's not very clever...
What you can do about it is to replace the default exception handler (see this function), call getMessage on the exception and parse the HTML error page to extract the message. Then you can print the error message and kill the script. Like this (in PHP 5.3):
set_exception_handler(
function (Exception $e) {
die(parse_html_error_page($e->getMessage()));
}
);
OK, I misunderstood the question. If the script you're testing catches the error and then echoes an error page, then this has nothing to do with exceptions. You can use the ob_ family:
ob_start();
include $file;
$contents = ob_get_contents();
if (result_is_error($contents))
die(extract_error_from_result($contents));
else
echo $contents;
ob_end_clean();

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