Codeigniter extended core exception class function issue - php

I have extend codeigniter native library (exceptions) and define a new function.
Here is code
class MY_Exceptions extends CI_Exceptions {
public function __construct() {
parent::__construct();
}
public function show_error($heading, $message, $template = 'error_general', $status_code = 500) {
try {
} catch (Exception $e) {
}
}
public function custom_errors($id, $message) {
try {
//some code here
} catch (Exception $e) {
}
}
}
I put this above class in application/core/My_Exceptions.php for autoload as mention in documentation. https://www.codeigniter.com/user_guide/general/core_classes.html
The problem is, i can't access function custom_errors($id, $message) in controller while show_error() is available in the same controller
I try like this
$this->my_exceptions->custom_errors($id, $message)
And
$this->exceptions->custom_errors($id, $message)
But get this error "Call to a member function custom_errors() on a non-object"
If codeigniter autoload it than it should be available here.
Please help me what i am doing wrong?

Related

Call to undefined method App\Helpers Laravel

I want to call function payrollProcess from another class inside my controller.
here's my code :
public function save(Request $request, $obj = null)
{
PayrollHelper::payrollProcess($PayrollPeriod);
return view('payroll_process.form');
}
and this is payrollHelper class code :
<?php
namespace App\Helpers;
use App\Helpers\Exceptions\ValidationException;
use App\Models\Config;
use App\Models\Driver;
use App\Models\DriverPayable;
use App\Models\PayrollPeriod;
use Carbon\Carbon;
use Exception;
use Illuminate\Support\Facades\Log;
final class PayrollHelper {
public static function processPayroll(PayrollPeriod $payrollPeriod)
{
try {
$drivers = Driver::where('active', true)->get();
foreach ($drivers as $driver) {
$payable = $payrollPeriod->driverPayables()
->where('driver_id', $driver->id)->first();
if (!$payable) {
$payable = new DriverPayable;
}
$payable->payrollPeriod()->associate($payrollPeriod);
$payable->driver()->associate($driver);
if (!$payable->save()) {
\Log::info($payable->errors());
throw new ValidationException($payable->errors());
}
}
} catch (Exception $e) {
Log::error($e);
SessionHelper::setMessage(
'Unable to process payroll, Please contact system Administrator'
);
} catch (ValidationException $e) {
Log::info($e->errors);
SessionHelper::setMessage($e->errors);
}
}
}
?>
I got this error when i run it. Call to undefined method App\Helpers\PayrollHelper::payrollProcess()
any idea ?
In PayrollHelper class you have defined processPayroll method so in your controller
public function save(Request $request, $obj = null)
{
PayrollHelper::payrollProcess($PayrollPeriod);
return view('payroll_process.form');
}
you are accessing undefined method

How to catch ReflectionException in Laravel 5?

$module - is one of my classes, based on Interface and must be have public function getController. I can forget to add getController function in class, and after run i have this error:
ReflectionException in Container.php line 776:
Class App\Http\Controllers\ does not exist
and want to catch this exception, but this code not work:
try
{
\Route::get($module->getUrl(), $module->getController() . '#index');
}
catch (\ReflectionException $e)
{
echo 123123;
}
Code example:
namespace App\MyModules;
MyModuleManager::bindRoute();
interface MyModuleInterface
{
public function getUrl();
public function getController();
}
class MyClass implements MyModuleInterface
{
public function getUrl()
{
return '/url';
}
/*
* for example: this method i forgdet to add
* and in ModuleManager::bindRoute i want to cath exception
*
public function getController()
{
}
*/
}
class MyModuleManager
{
static public function bindRoute()
{
$module = new MyClass();
try
{
\Route::get($module->getUrl(), $module->getController() . '#index');
}
catch (\ReflectionException $e)
{
echo 123123;
}
}
}
In L5 you can handle this exception globally:
// Exceptions/Handler.php
use ReflectionException;
public function render($request, \Exception $e)
{
if ($e instanceof ReflectionException) {
// …
}
return parent::render($request, $e);
}

Unrecognized static methods - does the order matter?

I have the error
Call to undefined method Exception::message()
inside the object calling
Utils::message()
(I am catching the Exception and replacing by the message)
The file containing this object is included (require_once) by the top file together with another file defining Utils.
So my question is why the method of Utils is not recognized. All classes are included before the main code. Does the inclusion order matter? Any other hints?
EDIT. My Utils class:
class Utils {
private static $count;
private static $aggregateCount, $time, $last, $previous;
...
public static function message () {
echo "\n Count: ", self::$count++, " ";
$array = func_get_args();
foreach ($array as $entry) {
if (is_array($entry)) {
echo print_r($entry);
} else {
echo $entry;
}
}
}
...
}
And here is the function using the class:
public function updateManyWithId ($schema, array $bundle) {
foreach ($bundle as $hash) {
$id = $hash[ID_KEY];
$hash = $this->_adjustId($schema, $hash);
try {
$this->update($schema, $id, $hash);
} catch (Exception $e) {
Utils::message("Cannot update hash: ", $hash, $e->message());
}
}
}
$e->message() Is the problem. That refers to a class called Exception which is expected to have a method called message, but your Exception class does not have that method.
Look at the constructor of your Exception. You're passing in a message when you throw it, perhaps you're looking for $e->getMessage().
Read here: http://www.php.net/manual/en/exception.getmessage.php
To summarize, consider this:
class Exception {
//construct is used when you throw new Exception (instantiate the class)
public function __construct($message) {
$this->message = $message; //now the object has a "message" property
}
//this is a "getter" for this object's message
public function getMessage() {
return $this->message; //return the message
}
}
Note that the standard usage of getters/setters is to use getProperty and setProperty as the method name that returns/sets that property.

chain of resposibility code error for PHP

I have the following PHP code as chain of resposibility, I am using PHP5.4.9.
abstract class Logger
{
protected $next;
public function next($next)
{
$this->next = $next;
return $this->next;
}
public function run(){
$this->invoke();
if(null!=$this->next){
$this->next->invoke();
}
}
abstract public function invoke();
}
class EmailLogger extends Logger
{
public function invoke()
{
print_r("email\n");
}
}
class DatabaseLogger extends Logger
{
public function invoke()
{
print_r("database\n");
}
}
class FileLogger extends Logger
{
public function invoke()
{
print_r("file \n");
}
}
$logger = new EmailLogger();
$logger->next(new DatabaseLogger())->next(new FileLogger());
$logger->run();
the expect output is:
email
database
file
but the actually output:
email
database
I hope to implement chain of resposibility design pattern by PHP language, one abstract class and three or more classes to do something as a chain. but only the first two object works.
Anyting missing? Or PHP can not use this coding style under PHP5.4.9?
Thanks.
Replace
public function run() {
$this->invoke ();
if (null != $this->next) {
$this->next->invoke();
}
}
With
public function run() {
$this->invoke ();
if (null != $this->next) {
$this->next->run ();
}
}
please try $this->next->invoke() change $this->next->run()

Exception handling in php

I have this scenario:
Interface ClassInterface
{
public function getContext();
}
Class A implements ClassInterface
{
public function getContext()
{
return 'CONTEXTA';
}
//Called in controller class
public function Amethod1()
{
try {
//assuming that Helper is a property of this class
$this->helper->helperMethod($this);
} catch(Exception $ex) {
throw $ex;
}
}
}
Class B implements ClassInterface
{
public function getContext()
{
return 'CONTEXTB';
}
//Called in controller class
public function Bmethod1()
{
try {
//assuming that Helper is a property of this class
$this->helper->helperMethod($this);
} catch(Exception $ex) {
throw $ex;
}
}
}
Class Helper {
public function helperMethod(ClassInterface $interface)
{
try {
$this->verifyContext($interface->getContext());
//dosomething
} catch(\Exception $ex) {
throw $ex;
}
}
private function verifyContext($context) {
if (condition1) {
throw new \UnexpectedValueException('Invalid context.');
}
return true;
}
}
I want my controller class which calls Amethod1 and Bmethod1 to know the type of exception(s) thrown in the process. Is it advisable to rethrow an exception just like it was presented?
Do you think the throw-catch-throw-catch-throw structure reasonable in this case?
Yes, totally reasonable. But: your specific example can be simplified from:
public function Amethod1()
{
try {
//assuming that Helper is a property of this class
$this->helper->helperMethod($this);
} catch(Exception $ex) {
throw $ex;
}
}
To:
public function Amethod1()
{
//assuming that Helper is a property of this class
$this->helper->helperMethod($this);
}

Categories