开发者

Searching for some confirmation or guidance on usage of abstract class in Php

Basically I'm looking for feedback or guidance on something I've created this week at work. The problem was that I had two types of document upload. These types both shared methods like upload, isUploaded, move etc. But, in some instances they both had unique functionality.

So I thought the best approach to handle this would be to create an abstract class which contains the common functionality and 2 separate classes which extend the base abstract class in order to inherit the common functionality.

So I have:

abstract class Upload {

 protected $_id;
 protected $_name;
 protected $_dbTable;

 abstract public function create(Filter $filter) {}
 abstract public function update(Filter $filter) {}

 public function __construct($id){
  if(!is_null($id)){
   $class = new get_called_class();
   return new $class($id);
  }
 }

 protected function upload(){
  //Code implemented
 }

 protected function isUploaded(){
  //Code implemented
 }

 protected function move(){
  //Code implemented
 }

}

Class Book_Upload extends Upload {

 $dbTable = 'book';

 public function __construct($id){
  //Database stuff to obtain record information
  //Set protected member variables
  $results = $databaseCall();
  $this->_id = $results['id'];
  $this->_name = $results['name'];
 }

 开发者_Go百科public function create(Filter $filter) {
  //Code implemented
 }

 public function update(Filter $filter) {
  //Code implemenetd
 }

 //Other unique functions

}

Class Magazine_Upload extends Upload {

 $dbTable = 'magazine';

 Same as Booking_Upload but with additional functionality
 plus abstract methods

}

My query is, am I using abstract methods correctly? Have I followed the correct path. Also, I'm not sure I need the construct in the abstract class. What if someone attempts to call $upload = new Upload($id)?


Any class should provide a single type of functionality (Single Responsibility Principle, example: Single Responsibility Principle - A hard to see example?).

An upload class must only deal with uploads. Without more code, I smell an over-functional class from your words that tries to accomplish both the upload and document-spesific tasks.

So before going that way, you should define well what these classes will be doing. Are those document-spesific functionalities really related to the actual act of uploading?


You're extending class doesn't call parent::__construct() so the abstract __construct won't make any difference.

You are using abstract classes correctly; they are base classes that are to be built upon by other classes that share common functions and/or will have the same functionality but is implemented differently.

Abstract classes are a base to be built upon that provide common functionality and structure to other classes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜