php class extend approch vs static approch,which one is better
Approch 1:
class Storage extends SaeStorage {
public function save($data,$name){
if (! $this->write ( ST_DOMAIN, $name, $data )){
$error_message = $this->errmsg();
$result['error'] = $error_message;
return $result;
}else{
$url = $this->getUrl ( ST_DOMAIN, $name );
return $url;
}
}
}
approach 2:
class Storage {
public static function save($data,$name){
$SaeStorage = new SaeStorage();
if (! $SaeStorage->wr开发者_开发知识库ite ( ST_DOMAIN, $name, $data )){
$error_message = $this->errmsg();
$result['error'] = $error_message;
return $result;
}else{
$url = $SaeStorage->getUrl ( ST_DOMAIN, $name );
return $url;
}
}
}
I propose to use dependency injection pattern. Here is example
If you are going to use the SaeStorage class throughout the Storage class then approach 1 makes much more sense. It saves you having to instantiate a new object every time you want to use a method or property in the extended class.
Its really a design question. Both approaches are good, depends on your needs.
The first one is better if you want all the SaeStorage functionality in Storage, the second if you dont need it, only in the save method.
Anyway, I suggest the first one here, because you can use it in places where SaeStorage is in use too.
Depends on what do you mean by better. I'm keeping performance out of question as the difference in performance between the two approaches will be very minimal (if at all there is any) and can be ignored.
Then it is entirely a design question. Things for which you need to find answers are:
- Do you want your clients to seamlessly replace SaeStorage with Storage, and SaeStorage is a special type of Storage? If yes then extend otherwise don't.
- Is SaeStorage just a behavior? For example Storage is a storage device and the way they save things varies. SaeStorage is just one of the ways you save things. Then use second approach, which is kind of a strategy pattern.
- Even if SaeStorage is a special storage you might want to use strategy pattern to decouple behavior from interface.
精彩评论