So far I have a PHP
class with the constructor
public function __construct ($identifier = NULL)
{
// Return me.
if ( $identifier != NULL )
{
I'm really surprised that for 4 years none of the 22k viewers suggested creating private constructor and a method that attempts to create an object like this:
class A {
private function __construct () {
echo "Created!\n";
}
public static function attemptToCreate ($should_it_succeed) {
if ($should_it_succeed) {
return new A();
}
return false;
}
}
var_dump(A::attemptToCreate(0)); // bool(false)
var_dump(A::attemptToCreate(1)); // object(A)#1 (0) {}
//! new A(); - gives error
This way you get either an object or false (you can also make it return null). Catching both situations is now very easy:
$user = User::attemptToCreate('email@example.com');
if(!$user) { // or if(is_null($user)) in case you return null instead of false
echo "Not logged.";
} else {
echo $user->name; // e.g.
}
You can test it right here: http://ideone.com/TDqSyi
I find my solution more convenient to use than throwing and catching exceptions.
I wouldn't put too much in the construct. You should consider a static functin that create the User (factory) instead of putting everything in the constructor. Thus, you can still use your user object without having to call implicitly the load function. This will save you pain.
public function __construct(){}
public function setIdentifier($value){
$this->identifier = $value;
}
public function load(){
// whatever you need to load here
//...
throw new UserParameterNotSetException('identifier not set');
// ...
// if user cannot be loaded properly
throw new UserNotFoundException('could not found user');
}
public static function loadUser($identifier){
$user = new User();
$user->setIdentifier($identifier);
$user->load();
return $user;
}
Sample usage:
$user = new User();
try{
$user->setIdentifier('identifier');
$user->load();
}
catch(UserParameterNotSetException $e){
//...
}
catch(UserNotFoundException $e){
// do whatever you need to do when user is not found
}
// With the factory static function:
try{
$user2 = User::loadUser('identifier');
}
catch(UserParameterNotSetException $e){
//...
}
catch(UserNotFoundException $e){
// do whatever you need to do when user is not found
}