Implementing Interface and Autoloading Classes - php

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

Related

Displaying WPDB error in try catch not working?

I am trying to create a Class that will be using a external api and wpdb class however i am having issues already in the try catch block please confirm the below is correct:
<?php
require_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-config.php' );
require_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-includes/wp-db.php' );
class LoLApi
{
private $database;
public function __construct()
{
try {
$this->database = new wpdb('user', 'pass', 'table', '127.0.0.1');
$this->database->show_errors();
} catch (Exception $e) {
return $e->getMessage();
}
}
}
?>
in the other page:
<?php
session_start();
require 'includes/lolapi.class.php';
$api = new LoLApi;
exit();
?>
You should be checking instead whether it returns a WP_Error object. If the WP_Error class doesn't exist it will just die and dump an error message. Nowhere does it actually throw an exception.
If you include wp-load.php you'll have the WP_Error class available and you can check for it in the data returned. You could also extend the wpdb class and override the db_connect method to throw a proper exception instead of killing the script on a connection failure.

can't figure what might causing this error when creating PDO object

i am following a tutorial to create an OOP based login system.I did everything accordingly but while creating pdo i am getting an error in DB.php file in line 15.Can't figure out the reason for this error.Been stuck there for some time.Can anyone help me out with this error .The code might look long but it is a piece of cake for you i promise.There are FOUR php files.
1.init.php file holds the ingredients to create a new PDO() object.
2.config.php file is used to get data from init.php file as string is passed to it as ('mysql/host') type and use explode() function to extract data from it.
2.DB.php file is used to connect to database.
The error i am getting is
DB.php file:
class DB{
private $_instance=null;
private $pdo,
$query,
$error=false,
$results,
$count=0;
private function __construct(){
try{
$this->$pdo=new PDO('mysql:host='.Config::get('mysql/host').';dbname='.Config::get('mysql/db'),Config::get('mysql/user'),Config::get('mysql/password'));
}catch(PDOException as $e){
echo $e->getMessage();
}
}
public static function getInstance(){
if(!isset(self::$_instance)){
self::$_instance=new DB();
}
return self::$_instance;
}
}
Config.php file:
class Config{
public static function get($path){
if($path){
$config=$GLOBALS['config'];
$arr=explode('/',$path);
foreach($arr as $bit){
if(isset($config[$bit])){
$config=$config[$bit];
}
}
return $config;
}
}
}
init.php file:
session_start();
$GLOBALS['config']=array(
'mysql'=>array(
'host' => 'localhost',
'db' => 'login',
'user' => 'root',
'password' => ''
)
);
spl_autoload_register(function($class){
require_once 'c:/xampp/htdocs/login/classes/'.$class.'.php';
});
require_once 'c:/xampp/htdocs/login/function/sanitize.php';
index.php file:
require_once 'c:/xampp/htdocs/login/core/init.php';
DB::getInstance()->query('SELECT name FROM table WHERE id=1');
Your error message is a Parse Error. This means the PHP interpreter/processor/program tried to read your file, but found a syntax error, and had to stop. If you look at Line 15 of DB.php (per the error message)
}catch(PDOException as $e){
You'll see the problem. This isn't valid PHP syntax -- you probably want
}catch(PDOException $e){
The PDOException bit of that is a a class type hint for the exception handling code -- there's no need to use the as.

Creating a new instance of another file

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

PHP SQLite3 error?

How do I know if there's an error if I did $db = new SQLite3("somedb.db"); in PHP? Right now the $db doesn't really give me any sort of error?
I can check for file existance, but I'm unsure if there could be any other errors when I open a connection.
You should enable exceptions and instantiate in a try-catch block.
It is not obvious from the documentation but if you use the constructor to open the database it will throw an exception on error.
Further if you set the flag SQLITE3_OPEN_READWRITE in the second argument then it will also throw an exception when the database does not exist (rather than creating it).
class Database extends SQLite3
{
function __construct($dbName)
{
$this->enableExceptions(true);
try
{
parent::__construct($dbName, SQLITE3_OPEN_READWRITE );
}
catch(Exception $ex) { die( $ex->getMessage() ); }
}
Try:
echo $db->lastErrorMsg();

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