PHP OOP: a unique method for each type of argument?

I write a little homegrown ORM (academic interest). I try to stick to the concept of TDD as a training exercise, and as part of this exercise, I am writing API documentation when developing a class.

Random point: I'm working on a classic getCollection class class. I want him to be able to receive collections of X assets (say, blog posts) for a specific user, as well as collections based on an arbitrary array of numerical values. So you can have a method like any of these

$User = $UserMapper->load(1);
$ArticleCollection = $ArticleMapper->getCollection(range(10,20));
$ArticleCollection = $ArticleMapper->getCollection($User);
$ArticleCollection = $ArticleMapper->getCollection($User->getId());

So, when writing documentation for the getCollection method - I want to declare the @param variable in Docblock. Is it better to have a unique method for each type of argument, or is it acceptable to have a method that delegates to the correct inner method / class based on the type of the argument?

+3
source share
3 answers

It is valid to have a method that delegates to the correct internal method. You can do it like this:

@param Array|User|Integer $argName optional explanation

but again, no one bothers you to have one method

public function getCollectionByRange(array $range)
public function getCollectionByUser(User $user)
public function getCollectionByUserId($id)

, magic __call, , , (ZF ). @method DocBlock. , , / .

, , , usecase.

+6

, , PHP ( PHP5) , , , Java. PHP :

: PHP "" - . , .

:

class ArticleMapper {
   public function getCollection($param) {
      if (is_array($param)) { $this->getCollectionByArray($param); }
      if (is_int($param)) { $this->getCollectionByInt($param); }
      if (is_a($param, 'User')) { $this->getCollectionByUser($param); }
   }
   private function getCollectionByArray(array $param) { ... }
   private function getCollectionByInt($param) { ... }
   private function getCollectionByUser(User $param) { ... }
}

.

+1

- , (PHP , , ADA, Java, # ++, ):

[...]
/**
 * @param  User|array|integer $user
 * @return array
 */
public function getCollection($user) {
    // perhaps a switch-case would be better here
    if ($user instanceof User) {
        // do what has to be done if you passed in a User object
    } else if (is_int($user) {
        // do what has to be done if you passed in a user id
    } else if (is_array($user)) {
        // do what has to be done if you passed in an array of user ids
    }
}
[...]
+1
source

Source: https://habr.com/ru/post/1744520/


All Articles