I am using method chaining for my class structure.
So my problem is that , how could i break my chain when error occurred in some function.
Below is my code:
<?php
class demo
{
public __construct()
{
$this->a='a';
$this->b='b';
$this->error = false;
}
public function demo1()
{
// Some operation here
// Now based on that operation
if(Operation success)
{
return $this;
}
else
{
// What should i write here which break the chain of methods.
// It will not execute the second function demo2
}
}
public function demo2()
{
// Some operation here
// After function Demo1
}
}
$demoClass = new demo();
$demoClass->demo1()->demo2();
?>
EDIT:
$demoClass = new demo();
try
{
$demoClass->demo1()->demo2();
}
catch(Exception $e)
{
echo "Caught Exception:->".$e->getMessage();
}
Thanks
Avinash
I think you need to throw user exception there.
if(Operation success)
{
return $this;
}
else
{
// What should i write here which break the chain of methods.
// It will not execute the second function demo2
throw new Exception('error');
}
Related
Let's say I'm coding a command. How would I stop it completely in the middle of it running?
Example:
public function handle()
{
if (!$this->good_times) {
$this->error('Bad times');
$this->exit();
}
// continue command stuff
}
I have tried:
throw new RuntimeException('Bad times');
But that dumps a bunch of ugliness in the terminal.
Just use a return statement instead of throwing an exception. Like...
public function handle()
{
if (!$this->good_times) {
$this->error('Bad times');
// $this->exit();
// throw new RuntimeException('Bad times');
return;
}
// ...
}
Ran into this problem as well.
Just create an exception that implements ExceptionInterface.
use Exception;
use Symfony\Component\Console\Exception\ExceptionInterface;
class ConsoleException extends Exception implements ExceptionInterface
{
}
now when you throw the error:
throw new ConsoleException('Bad times');
You get the error without the stack trace.
try to used like that
public function handle()
{
try {
if(!isset($x)){
throw new \Exception('not found');
}
}catch(\Exception $e){
exit($e->getMessage());
}
$this->info("test here");
}
private function foo()
{
if (/* exception trigger condition */) {
throw new \Exception('Exception message');
}
// ...
}
public function handle()
{
try{
$this->foo();
} catch (\Exception $error){
$this->error('An error occurred: ' . $error->getMessage());
return;
}
$this->comment('All done');
}
Use return with the exit code number:
public function handle()
{
$this->error('Invalid parameter: thiswillfail');
return 1;
}
Return a 0 if all is ok, a non-zero positive value on errors:
$ ./artisan mycommand thiswillfail; echo $?
Invalid parameter: thiswillfail
1
This works with at least Laravel 6 onwards.
You can use return or exit if you want to stop the command from within a function.
public function handle()
{
return;
}
protected function stop() {
exit;
}
public function handle()
{
$this->stop();
}
Here is my code:
public function call_with_attempts($class_obj, $method_name,array $params = [], $attempts = 5) {
while ($attempts-- > 0) {
try {
if (call_user_func(array($class_obj, $method_name), $params)['result_code'] == '01') {
// log success
return $class_obj->$method_name();
}
throw new Exception("failed");
} catch (Exception $e) {
trigger_error($e->getMessage());
// log the error
}
}
}
I call it like this:
$url = 'www.example.com';
$obj = new Profile($url);
all_with_attempts($obj, 'mymethod');
And here is Profile class:
class profile {
public $url;
public function __construct( $passed_url )
{
$this->url = $passed_url;
}
public function mymethod(){
// do stuff
}
}
Any my code (when I call this function all_with_attempts($obj, 'mymethod');). throws this error:
Missing argument 1 for App\classes\Profile::__construct(), called in {/path}
As you know, this error ^ means Profile class will be create again .. well that's not what I want. I want to use $obj. How can I do that?
I basically need to call one of two constructors from my PHP class dependent on wheter or not verification is needed.
My current code looks like this:
class Event extends Generic {
private $user_id;
function __construct($user_id=null) {
$this->user_id = $user_id;
}
public function verify($user_id=null, $identifier=null) {
if (parent::verifyUser($user_id, $identifier)) {
return new Event($user_id);
}
else {
// what gets retruend here in the event of a failure???
}
}
public function noverify($user_id=null) {
return new Event(user_id);
}
}
Calling the code like so:
$event = new Event();
$obj1 = $event->noverify(5);
$obj2 = $event->verify(5, 100);
I'm really not clear how I should handle the event of a failed constructor if the condition inside fails. Am I heading down the wrong path here?
I would either throw an Exception or return FALSE:
else {
throw new Exception('verification failed');
}
or
else {
return FALSE;
}
I am getting unexpected T_TRY, expecting T_FUNCTION error message and am not sure as too why am getting that, can't we use try and catch block inside class like this:
class Processor
{
protected $dao;
protected $fin;
try
{
public function __construct($file)
{
//Open File for parsing.
$this->fin = fopen($file,'w+') or die('Cannot open file');
// Initialize the Repository DAO.
$this->dao = new Dao('some name');
}
public function initiateInserts()
{
while (($data=fgetcsv($this->fin,5000,";"))!==FALSE)
{
$initiate_inserts = $this->dao->initiateInserts($data);
}
}
public function initiateCUpdates()
{
while (($data=fgetcsv($this->fin,5000,";"))!==FALSE)
{
$initiate_updates = $this->dao->initiateCUpdates($data);
}
}
public function initiateExecuteIUpdates()
{
while (($data=fgetcsv($this->fin,5000,";"))!==FALSE)
{
$initiate_updates = $this->dao->initiateIUpdates($data);
}
}
}
catch (Exception $e)
{
}
}
You can't put all your method definitions into one try-catch block.
Instead of
class Foo {
try {
public function func1() { }
public function func2() { }
}
catch(Exception $e) {
}
}
you have to use
class Foo {
public function func1() {
try {
...
}
catch(Exception $e) {
...
}
}
public function func2() {
try {
...
}
catch(Exception $e) {
...
}
}
}
Don't try-catch inside of each method, you could simply try-catch when you use your class:
try {
$p = new Processor($file);
$p->initiateInserts();
$p->initiateCUpdates();
// and so on...
} catch (Exception $e) {
// handle the error...
}
This way your class will be much cleaner and you can decide what to do with errors. Especially if you use your class in multiple places - you can have customized error handling for each case.
You can't have any "do this stuff"-code in a class outside of a method. There is nothing to "try to do" inside those curly brackets, because the stuff inside is just method definitions.
I am learning OOP with PHP. I am creating a class to extract XML data from a website. My question is how do I stop the given object from executing more methods if there is an error with the first method. For example, I want to send the URL:
class GEOCACHE {
public $url;
public function __construct($url)
{
$this->url=$url;
if (empty($this->url))
{
echo "Missing URL";
}
}
public function secondJob()
{
whatever
}
}
when I write like this:
$map = new GEOCACHE ("");
$map->secondJob("name");
How do I prevent the secondJob method from being executed in that given object without the script terminating?
Throw an Exception in the constructor, therefore the object will never be created
public function __construct($url)
{
$this->url=$url;
if (empty($this->url))
{
throw new Exception("URL is Empty");
}
}
You can then do something like this:
try
{
$map = new GEOCACHE ("");
$map->secondJob("name");
}
catch ( Exception $e)
{
die($e->getMessage());
}
Consider using exceptions in order to control the flow of the script. Throw an exception in the constructor, and catch it outside.
class GEOCACHE {
public $url;
public function __construct($url)
{
$this->url=$url;
if (empty($this->url))
{
throw new Exception("Missing URL");
}
}
public function secondJob()
{
whatever
}
}
try{
$map = new GEOCACHE ("");
$map->secondJob("name");
}catch($e){
// handle error.
}
Throw an exception from __construct
public function __construct($url)
{
if(null == $url || $url == '')
{
throw new Exception('Your Message');
{
}
then in your code
try
{
$geocache = new Geocache($url);
$geocache->secondJob();
// other stuff
}
catch (exception $e)
{
// logic to perform if the geocode object fails
}