multiple functions is one big function in PHP?

萝らか妹 提交于 2019-12-24 07:18:10

问题


so I'm writing DataBase class which will be an encapsulation layer between PHP Controller and MySQL View.

interface iDataBase {
    public function drug($action, $drug);
    public function company($action, $company);
    public function activeIngredient($action, $activeIngredient);
}

At First I thought of making all setters and getters seperate like getAllDrugs(), updateDrug(), removeDrug(), getForUpdate(), getDrug() and so one, but then I realised that I was polluting database interface with too much functions, plus this is a very small-scale version, I'm considering adding much-more classes and much more functionality. So, instead of using a lot of function I just setteled for 3. $action will determine what kind of thing does user want to do with certain class. so, for now, possible actions are these: "add", "getAll", "getForUpdate", "update", "remove"

but these functions masked by $action have different things to do, so their their return result is different and second argument can also be different.

Is my solution a good practice? I'm sure many of you had the same problem, how did you solve it? Are there any possible problems?

P.S. Drug, Company, ActiveIngredient are all classes


回答1:


A function should have clearly defined, narrow responsibilities with clearly defined, minimalist return types. If you start to create "god functions" which do everything and the kitchen sink depending on what arguments you pass, you're going heavily into the territory of hard to maintain spaghetti code. You do not want a function that does A and returns B if you pass it X, but does C and returns D if you pass it Y etc...

It is a good idea to start concrete and generalize over time as you see similar patterns emerge. So, create the methods you actually need:

public function findUserById($id)
public function findUserByEmail($email)
public function updateCompanyName($id, $newName)

If you find you have shared code between these functions, unify the code behind the scenes to keep it DRY:

public function findUserById($id) {
    return $this->find('SELECT * FROM user WHERE id = ?', $id);
}

public function findUserByEmail($email) {
    return $this->find('SELECT * FROM user WHERE email = ?', $email);
}

protected function find($query, $arg) {
    ...
}

Don't start the other way around, thinking you "only need X,Y and Z" which seem similar enough to be unified into one method, then later finding out there are small differences between X, Y and Z and littering your code with special cases for each. That just leads to functions which are either ginormous or so general they basically do nothing on their own.




回答2:


What you are likely looking for is called a TableDataGateway (emphasis mine):

A Table Data Gateway holds all the SQL for accessing a single table or view: selects, inserts, updates, and deletes. Other code calls its methods for all interaction with the database.

This means you will have one generic database adapter, for instance a PDO object. You inject this into your various TDG's. The TDG's then use that adapter to CRUD data from the database.

Example

class CompanyTableGateway
{
    private $dbAdapter;

    public function __construct(DBAdapter $dbAdapter)
    {
        $this->dbAdapter = $dbAdapter;
    }

    public function create($name, $street, $whatever)
    {
        $this->dbAdapter->exec( 'INSERT INTO companies …' );
    }

    public function findById($id) 
    {
        return $this->dbAdapter->exec(
            sprintf('SELECT * from companies where id = %d', $id)
        );
    }

    // more methods …
}

If you have multiple of these Gateways, you can abstract the general CRUD logic into an Abstract class and then extend the concrete Gateways from it.

You will then use a TableModule or similar other object to call the methods on the individual Gateways.




回答3:


The never ending discussion of Separation of Concerns vs Single Responsibility Principle.

  • Separation of Concerns (SoC) – is the process of breaking a computer program into distinct features that overlap in functionality as little as possible. A concern is any piece of interest or focus in a program. Typically, concerns are synonymous with features or behaviors. http://en.wikipedia.org/wiki/Separation_of_concerns

  • Single Responsibility Principle (SRP) – every object should have a single responsibility, and that all its services should be narrowly aligned with that responsibility. On some level Cohesion is considered as synonym for SRP. http://en.wikipedia.org/wiki/Single_responsibility_principle

Try to get the best of both, and model your classes accordingly.




回答4:


What I would recommend you doing is do a global database class, which controls the basic input / output of the database, and then extend this down to each table.

An example of this could be a Users table. What you can do to this table is

  1. Create
  2. Update
  3. Delete

You will then extend the Super Database Class, with a Users Class, which will have getters and setters for each function you want to have, ie:

class Users extends DatabaseClass {
    public function update ( $params )
    {
        // Make the code for an update, and let the SuperClass execute the code.
        ...
    }

    public function add ( $params )
    {
        ...
    }

    public function delete ( $params )
    {
        ...
    }
}

This will allow you to later, easily add more functionality to the Users table, and optimize queries specifically for the table/data you're using.



来源:https://stackoverflow.com/questions/13048252/multiple-functions-is-one-big-function-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!