B
B
Boris Yakushev2016-02-24 14:12:31
PHP
Boris Yakushev, 2016-02-24 14:12:31

Whether correctly implemented connection to a DB?

Good afternoon, I'm making a test site in php using mvc, according to this topic. But it does not implement a connection to the database.
How I implemented it:
In core/model.php, I created a db method containing a database connection.

class Model
  {
    static function db()
    {
      define('HOST', 'localhost');
      define('USER', 'blog');
      define('PASS', '12345');
      define('DB', 'blog');

      $db = new mysqli(HOST, USER, PASS, DB);
      if ($db->connect_errno) {
        echo "Не удалось подключиться к MySQL: {$db->connect_error}";
      }
      return $db;
    }

    public function get_data()
    {}
  }

Further, in the class of the heir, I compose a query
class Model_Portfolio extends Model
  {
    public function get_data()
    {
      $link = self::db();
      $query = "SELECT * FROM blog ORDER BY id DESC";
      $result = $link->query($query);
      while ($row = $result->fetch_assoc()) {
        $articles[] = $row;
      }
      $link->close();
      return $articles;
    }
  }

In the controller I connect the model and the template
class Controller_Portfolio extends Controller
  {
    function __construct()
    {
      $this->model = new Model_Portfolio;
      $this->view = new View;
    }

    function action_index()
    {
      $data = $this->model->get_data();
      $this->view->generate('portfolio_view.php', 'template_view.php', $data);
    }
  }

Well, I display it on the page with a simple cycle.
How correct is this approach, and / or how to improve it, maybe I missed something?
Thanks everyone for the advice.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
X
xfg, 2016-02-24
@xfg

echo "Unable to connect to MySQL: {$db->connect_error}";

In such cases, you need to throw an exception. There is no connection to the database - there is no point in executing the program, you need to die. And if it makes sense, then catch the abandoned exception at other levels and somehow handle this situation.
Sew up the connection in the model - bad. It is better to create a separate Connection class for this. Instead of mysqli, it is better to use PDO, not to be tied to a specific database.
Instead of raw SQL queries, it is better to take a ready-made DAO class or write your own so as not to depend on the SQL query syntax of a particular database.
Closing the connection to the database in the model is bad. It is better to close the connection to the database at the application level, after the controller action has completed.
In general, it would be worth reading about GRASP and SOLID. Inheritance is not always good, sometimes it's better to use composition and depend on abstractions rather than concrete implementations. Then it will be possible to polymorphically replace one implementation with another without breaking OCP from SOLID.
Take a look at any popular framework to understand how and what roughly works.

K
Kirill Danshin, 2016-02-24
@kirill_danshin

I would recommend not to store data for connecting to the database in constants. I would write it like this:

class Model
  {
    private static $db_creds = [
        'user' => 'blog',
        'host' => 'localhost',
        'pass' => '12345',
        'db'    => 'blog'
    ];

    static function db()
    {
      // закешируем соединение, зачем каждый вызов создавать новое?
      static $db;
      if (is_null($db)) {
          $db = new mysqli(
              self::$db_creds['host'], 
              self::$db_creds['user'], 
              self::$db_creds['pass'], 
              self::$db_creds['db']
          );
          if ($db->connect_errno) {
              echo "Не удалось подключиться к MySQL: {$db->connect_error}";
              // в следующий вызов попробуем еще раз
              $db = null;
          }
      }
      return $db;
    }

    public function get_data()
    {}
  }

Also would advise to use exceptions for handling of errors. They do not need to be shown to the user, it is better to process them, for example, show a cached version, redirect to another page, show a beautiful 500 notification, etc.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question