Z
Z
zeuss562017-03-10 21:53:57
PHP
zeuss56, 2017-03-10 21:53:57

Am I using OOP correctly?

  • All classes are organized into folders according to namespaces (if used) in the class folder. Loaded by autoloader:
    # константы
    const DS = DIRECTORY_SEPARATOR;
    
    # установка текущей директории
    chdir(__DIR__);
    
    # инициализация автозагрузки
    spl_autoload_register(function($classname) {
      $filepath = 'class'.DS.str_replace('\\', DS, $classname).'.php';
      return file_exists($filepath) ? include_once($filepath) : false;
    });

  • First we create an interface, then we implement it (not always necessary).
  • If there is a variable that needs to be worked with for a long time, like a link to a database or a file, we make a private variable and a setter for it (often the constructor plays the role of the setter):
    private $db;
    
    function __construct(DB $db) {
      # установка класса БД
      $this->db = $db;
    }

  • Naturally, we take out the repeating code in separate methods. If there are similar methods in different classes, we move them to a separate class and use or inherit this class, depending on how common the functionality is.
  • Constants are defined outside of classes. Class constants only refer to those already defined outside:
    const LOCALES_TABLE = 'com_locales';
    
    class Locale {
      private $localestable = LOCALES_TABLE;
      # ...
    }

  • I use serialize()/unserialize() to store arrays in constants. It seems that in PHP7 this is no longer necessary, but I do not remember. Although this does not apply to OOP, it is interesting:
    const ABS_TABLES = serialize([
      'com_abs_str',
      'com_abs_int'
    ]);
    
    class ABS_Tables {
      private $tables;
    
      function __construct() {
        $tables = &$this->tables;
        $tables = unserialize(ABS_TABLES);
      }
      # ...
    }

  • In each method, the variables used are linked so as not to be written $this->when called. How correct is this?
    function GetLanguageByID($langid) {
      # линки
      $db         = &$this->db;
      $langstable = &$this->langstable;
      # ...
    }

    UPD (some comrades do not "catch up"):
    In many languages, if there is no variable with a certain name defined in the current variable space, it is searched higher. There is no such thing in PHP. If I access `$anyvar` from a class method, it won't find the variable and will throw a notice. And I want to access `$anyvar` class. So I rename `$this->anyvar` to `$anyvar` to write less `$this->` inside the method. And the link - that both reading and record in a variable worked.
  • To check the correctness of the input, I use this function so as not to check manually:
    private function CheckArgs(array $inputs) {
      foreach ($inputs as $input)
        if ($input === [] || $input === '' || $input === null)
          return false;
        return true;
    }
    
    function InsertValues($table, array $keys, array $values_arr) {
      # проверка всех аргументов
      if (!$this->CheckArgs(func_get_args()))
        return;
      # ...
    }
    
    function SelectValues($table, array $wherekeys = [], array $wherevalues = []) {
      # проверка определенных аргументов
      if (!$this->CheckArgs([$table]))
        return;
      # ...
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
OnYourLips, 2017-03-10
@zeuss56

All classes are organized into folders according to namespaces (if used) in the class folder. Loaded by autoloader
The idea is good, but the execution is terrible.
Be sure to master composer as soon as possible. This is the first thing you should start with.
Constants are defined outside of classes.
In no case. Exclusively within classes.
In each method, the variables used are linked - I just got tired of constantly writing $this-> when calling. How correct is this?
Forget about & for a year.
And to check the correctness of the input, I use this function
Not necessary. Just get familiar with the types.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question