The Cache: Technology Expert's Forum
 
*
Welcome, Guest. Please login or register. September 21, 2019, 06:22:06 AM

Login with username, password and session length


Pages: [1]
  Print  
Author Topic: Making PHP scripts error tolerant  (Read 5630 times)
Politik
Rookie
**
Offline Offline

Posts: 11


View Profile
« on: August 31, 2007, 09:48:45 AM »

Hey guys,

I am working on a comment poster and I want to make my script error tolerant so it can keep going through its loops. How would I go about doing this?  Huh? Thanks
Logged

No links in signatures please
vsloathe
vim ftw!
Global Moderator
Lifer
*****
Offline Offline

Posts: 1669



View Profile
« Reply #1 on: August 31, 2007, 10:08:17 AM »

Code:
<?php
$data
=GetInputFromAbovePost($AbovePost);
If(
$data==SUFFICIENT)
{
   
$AnswerToQuestion=ScroungeAroundInBrain($data);
   echo(
$AnswerToQuestion);
}
else
{
   echo(
"Insufficient data, please try again.");
}
?>


Running reply.php...

Insufficient data, please try again.
« Last Edit: September 04, 2007, 06:38:30 AM by vsloathe » Logged

hai
webprofessor
Rookie
**
Offline Offline

Posts: 15


View Profile
« Reply #2 on: August 31, 2007, 10:14:42 AM »

Depends on what you mean by error tolerant. Properly handling errors is a case by case thing and is tough to plan for beginners. Even experienced developers have issues as the complexity of the system increases.

Some general tips:
- if your in a loop and you don't want to trap and correct your error then trap it and "continue"..
- have you tried using any of the error handling techniques PHP has to offer? Check these links out
--- http://www.php.net/manual/en/ref.errorfunc.php
--- http://www.php.net/manual/en/language.exceptions.php
- choose to not display errors to your end user but catch them and log them. Show your user something else.. like an "OMFG my innards are busted"
- a great book on handling errors and programming in general is Code Complete I try to read it once a year.
- If you know about "exceptions", "throw", and "catch" in general programming then try and use that model where ever possible. If you don't know about those yet or are uncomfortable using them then look at the older error handling model ( your going to need to be familiar with it anyways to use the Exception model )

I hope thats a good starting point for you. Please feel free to explain more about what your trying to accomplish and what tolerant means in your project.

Logged

No links in signatures please
perkiset
Olde World Hacker
Administrator
Lifer
*****
Offline Offline

Posts: 10096



View Profile
« Reply #3 on: August 31, 2007, 10:34:20 AM »

- If you know about "exceptions", "throw", and "catch" in general programming then try and use that model where ever possible. If you don't know about those yet or are uncomfortable using them then look at the older error handling model ( your going to need to be familiar with it anyways to use the Exception model )

In any case, this is extremely important advice. Becoming comfortable with the notion that unexpecteds *do happen* and wrapping yourself in a layer where you can gracefully handle them is vital when fault tolerance is important.

With regards to authoring the program in the first place, I like to set error reporting during compilation to verbose, or in PHP error_reporting(E_ALL) for a bit and see every warning and message that comes out. Often, I can see what could potentially become a problem by looking very carefully at those messages. IMO, throw/catch is vital for handling unexpecteds, but seeing where the code is simply "uncomfortable" as opposed to broken can give you some really strong tips about how to anticipate future breakage.

/p
Logged

It is now believed, that after having lived in one compound with 3 wives and never leaving the house for 5 years, Bin Laden called the U.S. Navy Seals himself.
webprofessor
Rookie
**
Offline Offline

Posts: 15


View Profile
« Reply #4 on: August 31, 2007, 10:38:56 AM »

Also we should mention you need to have php5 to use the newer exception model.
Logged

No links in signatures please
Politik
Rookie
**
Offline Offline

Posts: 11


View Profile
« Reply #5 on: August 31, 2007, 11:30:27 AM »

Thanks for the help guys.

Quote
Please feel free to explain more about what your trying to accomplish and what tolerant means in your project.

In response to your questions WebProfessor, I want the script to continue throw the loop of posting to a blog and just skip the site where it just received an error. So if there is an error on webpage1 I want the script to record the error and continue to webpage2, etc., etc.

Logged

No links in signatures please
georgiecasey
Rookie
**
Offline Offline

Posts: 16


View Profile
« Reply #6 on: August 31, 2007, 04:45:31 PM »

Maybe he means more error tolerant in the actual posting to the blogs. What I do is test that the script works for one blog anyway and then let it fire away for 100 or 200 blogs and record all responses and go through the responses to spot any errors and then fix the script. I use PHP from the shell so just run script > log
and examine the log afterwards
Logged

No links in signatures please
DangerMouse
Expert
****
Offline Offline

Posts: 244



View Profile
« Reply #7 on: September 02, 2007, 04:03:04 PM »

This is a really interesting thread for a newb programmer such as myself, i'd like to follow it up with a quick question if its not too far off topic.

I'm starting to grapple with class architecture, or prehaps more accurately just moving away from linear scripts to a model thats a little more extendable, flexible and refined. I'm sure this is going to be a stupid question, but should methods (php) be returning values or true/false (and then assigning a class wide var appropriately) ?

Equally at which stage is it best to test the output from a function/method? Within the place its being called from, or within the function itself i.e. before returning a value. I've just noticed that I'm testing things all over the place with no consistancy  Roll Eyes, and I'm not sure what constitutes best practice.

Tips appreciated - it's times like this that I think maybe stumbling through blindly is not the most effective way to learn.

Cheers,

DM
Logged
perkiset
Olde World Hacker
Administrator
Lifer
*****
Offline Offline

Posts: 10096



View Profile
« Reply #8 on: September 02, 2007, 04:20:33 PM »

but should methods (php) be returning values or true/false (and then assigning a class wide var appropriately) ?
Methods are not required to have a return value. If you do something like this:

$myVar = $anObject->aMethodWithNoReturnValue();

$myVar will be null. But I don't understand the remains of your question... "and then assigning class wide var appropriately?" - are we talking about properties or methods here?


Equally at which stage is it best to test the output from a function/method? Within the place its being called from, or within the function itself i.e. before returning a value. I've just noticed that I'm testing things all over the place with no consistancy  Roll Eyes, and I'm not sure what constitutes best practice.
Appropriateness would be defined by the job at hand rather than standards here. I personally enjoy a lot of consistency in my programming because it makes "figuring out what I was thinking" a couple years later much easier. I guess the best way to answer is that if the object needs to know what the response was then clearly, evaluate and assign a value internal to the code of the method - but if the caller of the objects->method() needs to know, then pass a return value back out and evaluate in the main flow of the code. Hope that helps, again I'm not entirely sure of what you're asking.

/p
Logged

It is now believed, that after having lived in one compound with 3 wives and never leaving the house for 5 years, Bin Laden called the U.S. Navy Seals himself.
DangerMouse
Expert
****
Offline Offline

Posts: 244



View Profile
« Reply #9 on: September 02, 2007, 05:40:17 PM »

Looking back the question doesnt even make alot of sense to me either lol Smiley

The rather obscure reference to class wide vars, was meant to indicate properties. The situation I'm thinking of largely involves passing information between internal class methods to achieve a final output. The approach I've been taking thus far is to is to call methods, evaluate them as successful or not (true/false) and if successful put the output into a property to be used as required.

The workflow would look something like this:

mainMethod {

if helperMethod evaluates False
die or something similar
else
continue using property assigned by helperMethod
}

From what you just said I think part of my confussion may be due to incorrect use of properties, maybe using them as global containers when I shouldnt.

Definately helped, thanks.

DM


 
Logged
perkiset
Olde World Hacker
Administrator
Lifer
*****
Offline Offline

Posts: 10096



View Profile
« Reply #10 on: September 02, 2007, 06:04:47 PM »

Ah I think I get you - you're talking about validating the values assigned to a property - whether you do it at value-set time or usage-time, yes?

The magic class methods __get and __set will allow you to trap values that are set in your classes - but they carry a little price.

If you do not use __get and __set, then you could effectively do this:

$myObj->aCompletelyUnknownAndUselessValue = 0;

and the processor won't get upset. The variable name aCompletelyUnknownAndUselessValue will now be in the name space for <that> opbject. Additionally, you can do this:

$myObj->assumedStringValue = 12345;

... and now you're going to have to check the value contained in assumedStringValue before using it.

By using the __get and __set you can trap, evaluate and do work based on the getting and setting of values. If it's the wrong type of value then you can deny it - if it's an unknown variable you can deny it. This nicely wraps the "evaluation code" in a method that makes more sense than at execution time of something else. Additionally, you are less likely to have duplicate checking code if you use the properties more than once. Although out of context this code does not make a whole bunch of sense, here is the __get and __set routines at the base of a hierarichy of mine:

Code:
protected function __get($propName)
{
if (isset($this->requestList[$propName]['name'])) { return $this->requestList[$propName]['value']; }
if (isset($this->responseList[$propName]['name'])) { return $this->responseList[$propName]['value']; }
if (property_exists(get_class(), $propName)) { return $this->$propName; }

$this->error(get_class() . ": Unknown property '$propName'");
return false;
}

protected function __set($propName, $propValue)
{
// The __confirm func will either return true (handled) false (not a registered property)
// or throw an exception if it violates registered property's ... something.
if ($this->__confirm($propName, $propValue))
{
$this->requestList[$propName]['value'] = $propValue;
return true;
}

if (isset($this->responseList[$propName]['name']))
{
$this->error(get_class() . ": '$propName' is a read-only property.");
return false;
}

// last step - it might be a parameter that is added in a child class:
if (property_exists(get_class(), $propName)) { $this->$propName = $propValue; }

$this->error(get_class() . ": Unknown property '$propName'");
return false;
}

... I simply offer that as a way to see the code in action. As you can see, I have pretty much unlimited control of what will happen when a property is either set or asked for. By simply saying this:

public $myProperty;

in the class definition, then the line

if (property_exists(get_class(), $propName)) { $this->$propName = $propValue; }

will work correctly. If there is no definition for the property, then an exception will be thrown.

The price is simply complexity and a new requirement for you to handle *all* properties from then on, if you want things to be handled correctly. Is it worth the extra effort? I do this kind of thing about 20% of the time, tops. It's when I really really really need to make sure things are right before I go on and want to centralize that code. Hope this helps,

/p
« Last Edit: September 02, 2007, 06:09:33 PM by perkiset » Logged

It is now believed, that after having lived in one compound with 3 wives and never leaving the house for 5 years, Bin Laden called the U.S. Navy Seals himself.
DangerMouse
Expert
****
Offline Offline

Posts: 244



View Profile
« Reply #11 on: September 03, 2007, 12:06:31 AM »

Thanks Perk! Thats really interesting stuff, I'd never even heard of the __get and __set methods before you mentioned them - in fact I didnt realise there were more 'magic' methods over and above __construct and __destruct until I just looked them up!

I think the process may be overkill for the classes im knocking together atm but I think I may give it a try. I'm really keen to learn how to structure things in the best manner possible otherwise I figure I'll just end up with problems when I need to extend code or apply it to more varied situations.

I'd never seen the value in declaring properties at the start of a class definition before now - I suspected there was a reason besides procedural correctness but hadnt figured it out  D'oh!

I think maybe muddling through just with the aid of google and php.net may not be the best approach, can you recommend any good PHP 5 books? Particularly those that deal with Class structure well - I've read the concepts of OOP many times for a couple of different languages but find the paradigm examples used never seem to relate back to what I want to do.

Ta again, really helpfull.

DM
Logged
perkiset
Olde World Hacker
Administrator
Lifer
*****
Offline Offline

Posts: 10096



View Profile
« Reply #12 on: September 03, 2007, 09:00:02 AM »

I'd never seen the value in declaring properties at the start of a class definition before now - I suspected there was a reason besides procedural correctness but hadnt figured it out  D'oh!
In PHP4 the reasons were even more vague and personal preference. But in PHP5, since we now have exposure declarations (public, protected, private) it makes a lot more sense. It is *very good practice* to declare your vars in a class and then turn error_reporting to E_ALL for a bit - you'll get warnings if you're attempting to use vars that have not been declared, even though it won't die.

I think maybe muddling through just with the aid of google and php.net may not be the best approach, can you recommend any good PHP 5 books? Particularly those that deal with Class structure well - I've read the concepts of OOP many times for a couple of different languages but find the paradigm examples used never seem to relate back to what I want to do.
Some interesting ones I've come across (I own these 3 among lots of others):
* PHP Hacks, Herrington, O'Reilly press: lots of great gear spinners. Kind of like an electronics experiment kit - lots of things that really aren't complete projects, but make for good idea generators and skill expanders.
* PHP5 Power Programming, Gutmans, Bakken, Rethans, Prentice Hall: Good all around "Learn PHP5 Book." Doesn't stay in the basics for very long at all, works into class structure, design patterns, PEAR, websites, lots of good stuff.
* Object Oriented PHP, Lavin, No Starch Press: If you just want the objecty stuff this is a nice little read and reasonable reference book.

Hope that helps! Good luck dood, that's a great train you're on.
/p
Logged

It is now believed, that after having lived in one compound with 3 wives and never leaving the house for 5 years, Bin Laden called the U.S. Navy Seals himself.
vsloathe
vim ftw!
Global Moderator
Lifer
*****
Offline Offline

Posts: 1669



View Profile
« Reply #13 on: September 04, 2007, 06:39:16 AM »

Man I'm such a n00b, always forgetting the double "=" for my compare statements and assigning values inside of "if"s.
Logged

hai
georgiecasey
Rookie
**
Offline Offline

Posts: 16


View Profile
« Reply #14 on: September 13, 2007, 09:03:54 AM »

Some interesting ones I've come across (I own these 3 among lots of others):
* PHP Hacks, Herrington, O'Reilly press: lots of great gear spinners. Kind of like an electronics experiment kit - lots of things that really aren't complete projects, but make for good idea generators and skill expanders.
* PHP5 Power Programming, Gutmans, Bakken, Rethans, Prentice Hall: Good all around "Learn PHP5 Book." Doesn't stay in the basics for very long at all, works into class structure, design patterns, PEAR, websites, lots of good stuff.
* Object Oriented PHP, Lavin, No Starch Press: If you just want the objecty stuff this is a nice little read and reasonable reference book.

Hope that helps! Good luck dood, that's a great train you're on.
/p


Just downloaded the php5 power programming on the recommendation, very nice. The PHP shell script and php performance chapters especially, cheers.
Logged

No links in signatures please
Pages: [1]
  Print  
 
Jump to:  

Perkiset's Place Home   Best of The Cache   phpMyIDE: MySQL Stored Procedures, Functions & Triggers
Politics @ Perkiset's   Pinkhat's Perspective   
cache
mart
coder
programmers
ajax
php
javascript
Powered by MySQL Powered by PHP Powered by SMF 1.1.2 | SMF © 2006-2007, Simple Machines LLC
Seo4Smf v0.2 © Webmaster's Talks


Valid XHTML 1.0! Valid CSS!