Crud Energy with PDO

Asked

Viewed 3,709 times

2

The connection part is ready:

<?php

/*
* O padrão Singleton
*/

abstract class Conexao {

const USER = "root";
const PASS = "";

private static $instance = null;

private static function conectar() {

    try {   ##Tenta conectar ao banco se não funcionar cai no catch
        if (self::$instance == null): ##se não existir conexão com PDO receber a new   PDO() | a conexão
            $dsn = "mysql:host=localhost;dbname=phpoo";
            self::$instance = new PDO($dsn, self::USER, self::PASS);
        endif;
    } catch (PDOException $e) {
        echo "Erro: " . $e->getMessage(); #
    }
    return self::$instance; ## se ja exixtir uma conexão ele retorna a conexão
}

protected static function getDB() {
    return self::conectar();
} 

}

create an Abstract.php class (do the Generic CRUD here) with:

<?php

abstract class Abstrata extends Conexao {

protected function listar($where) {
    //implemente aqui seu código padrão para fazer update
    $db = parent::getDB();
}

protected function alterar($id, $data) {
     //implemente aqui seu código padrão para fazer update
    $db = parent::getDB();
}

protected function deletar($id) {
    //implemente aqui seu código padrão para fazer delete
    $db = parent::getDB();
}

protected function cadastrar($data) {
    //implemente aqui seu código padrão para fazer insert
    $db = parent::getDB();
    //outros códigos
}

}

And deposi only call external methods to the other classes. Will that way of implementing like this ?

  • Could you put your code and describe the difficulty/problem you are facing? take advantage and see how the site works on tour and how to ask

  • How do I enter code here?

  • Okay. Code on screen

  • 2

    Sincerity, what is the question @Kall.max? I don’t understand, if you can explain?

  • 1

    This CRUD that I am developing is Orietado the Object would like to make some modifications to it to be safer using PDO, ie stacking PDO on it. That’s what I’m not getting.

  • I think this is a ready-made code that you’re asking someone to modify it to suit your needs. Please follow the advice of @Lost and formulate so that we can help you on what you tried to do.

  • I’m not asking you to modify, , but to help me convert it to PDO. An improvement, As for the above code, it is my usefulness, I did, but taking a course on the Internet I saw the benefits of PDO and reading the http://php.net/manual/en/book.pdo.php documentation, I obeyed their benefic degree and Usuability decide to migrate to such for that reason asked help here.

  • It is difficult to adapt without knowing how you will use the class... Put an example of use that you use.

  • I am working here and trying to develop. I will put yes. Just finish some things here. Because what I’m trying to develop is a Generic CRUD with PDO on top of this existing OO, I’m trying to adapt. I can!! I believe.

  • 1

    Now I will make the class where will have the CRUD classes. And later just make the calls where I want doing the instances. Could you give me an example of an Insert or select Generico with PDO, who knows.

  • You want to create a Generic Persistence Model, where it saves deletes list as you pass a configuration?

  • @Kall.max in my opinion this is the kind of code we should not waste time programming! What business value is this bringing to your system? I recommend using packages ready for this type of situation, in my reply I tried to teach how to use a ready DBAL if you have difficulties and interest leave a comment

Show 8 more comments

2 answers

3

Very sensible what you’re trying to do, but my first tip is: just do it for didactic reasons. Calm down, I already explain why, there are packages ready that do what you want and in a very good and tested way and with community support, for DBA Layer I use the Doctrine DBAL that I will teach to use here.

Installation

This is the installation using commiserate (recommend). Add the following dependency to your Composer.json and update its dependencies.

"require": {
        "doctrine/dbal": "2.3.4"
    },

Doctrine DBAL is already configured to work with the autoloader of Poser, so you don’t need to do ANYTHING else to install it. Easy doesn’t ?

Using

Now you have a DBA Layer installed, you just need to configure the connection data to be able to exit using.

Configuring connection

use Doctrine\DBAL\Configuration;
use Doctrine\DBAL\DriverManager;

$config = new Configuration();

$connectionParams = array(
    'dbname' => 'mydb',
    'user' => 'user',
    'password' => 'secret',
    'host' => 'localhost',
    'driver' => 'pdo_mysql',
);

$conn = DriverManager::getConnection($connectionParams, $config);

Performing updates

$conn->delete('user', array('id' => 1));
// DELETE FROM user WHERE id = ? (1)

$conn->insert('user', array('username' => 'jwage'));
// INSERT INTO user (username) VALUES (?) (jwage)

$conn->update('user', array('username' => 'jwage'), array('id' => 1));
// UPDATE user (username) VALUES (?) WHERE id = ? (jwage, 1)

Conducting consultations

$statement = $conn->prepare('SELECT * FROM user');
$statement->execute();
$users = $statement->fetchAll();

Performing queries with query Builder

The Querybuilder is a very good feature, it ALMOST abstracts SQL, it makes its much easier to change base if there is such a need. Here are some examples:

$queryBuilder = $conn->createQueryBuilder();

$queryBuilder
    ->select('id', 'name')
    ->from('users')
    ->where('email = ?')
    ->setParameter(0, $userInputEmail)
;
//SELECT


$queryBuilder
    ->insert('users')
;
//INSERT

$queryBuilder
    ->update('users')
;
//UPDATE

$queryBuilder
    ->delete('users')
;
//DELETE

Everything here is in official documentation which is very good!

  • +1 for content, but I think it validates the author’s willingness to create something of its own and can serve as a teaching basis.

  • Very good. I will try to do the installation, so you said it seems to be very simple and easy to work with it. How much creation I would like to do to understand the processes of a CRUD for continuous use in my future PHP systems. I am strongly analyzing now what will be more ultimate and agile for me today, in a matter of agility. I believe this class will be a hand on the wheel.

  • Cool, it’s important to do to understand learn, although you can learn using third-party packages as well. I created a micro framework that helped me a lot to understand patterns and OO, but for professional use strongly recommend not to reinvent the wheel.

  • Let me just understand one thing, Composer is a dependency for php. The Doctrine package must be downloaded and played in the project to be called right, just like Querybuilder. In other words, put everyone in the project and make the call as normal. Which I can understand in the explanation. That’s correct ?

  • First thing you have to do is install the Poser. To do this go to the root of your site and execute the following command $php -r "readfile('https://getcomposer.org/installer');" | php

  • How do I work with destitute machines, (in the company I use windows and in the home I use linux). How does installation in windows work ? So portable work -> USBSERVER[link]www.usbwebserver.net/

  • I did the installation of windows Composer searching the address in Root php.exe inside the Usbserver.

  • @Kall.max I find it interesting you open a new question to this

  • It was worth discovering how to do the installation. Any questions related to the code, I’ll post here.

  • Open question: http://answall.com/questions/31369/doctrine-dbal-opera%C3%A7%C3%B5es-do-bando-db

Show 5 more comments

1

If you want to use PDO because it is safer, then stop now.

The benefits of using PDO are:

  • Object-oriented interface to interact with the database (counterpoint the functions)
  • Unified database interface (instead of using specific functions for each database, you always use the same classes with PDO)

If you don’t have the need to interact with more than one database type in these classes, don’t mess with them. In both PDO and functions there are mechanisms that you will have to use to escape the values of the fields.

SOURCE: http://php.net/manual/en/intro.pdo.php

What you are trying to implement is a Tabledatagateway(source 1, source 2).

There are several implementations you can base on.

But we will continue with its implementation.

One way is, let your connection class be concrete (not abstract) and the getDb method as public.

Afterward:

<?php

 //include classe Conexao    

class TableDataGateway
{

    protected $_table;  

    protected function getDb()
    {
        return Conexao::getDb();
    }

    public function __construct($table)
    {
        $this->_table = $table;
    }

    public function insert($data)
    {
       //implemente aqui seu código padrão para fazer insert
       $db = $this->getDb();
       //outros códigos
    }

    public function delete($id)
    {
       //implemente aqui seu código padrão para fazer delete
    }

    public function update($id, $data)
    {
        //implemente aqui seu código padrão para fazer update
    }

    public  function select($where)
    {
        //implemente aqui seu código padrão para fazer update
    }
}

If you only need the basics, instantiating a Tabledatagateway('name_da_table') should be enough for most cases. If you want to link more different select or Insert methods, you can extend the class.

It would be good if you researched autoloaders and dependency injection to make your code a little more modern.

  • 1

    Why stop using the PDO if the reason is security?

  • He’s not using PDO, he wants to switch to PDO for the reason of adding more security to the application, if that’s the only reason, I’m sorry to inform you that the functions have the same level of security as PDO, if you send strings without escaping, they will run the same way, with or without PDO.

  • 1

    Agreeing to the answer I put this change as necessary, although at the immediate security level nothing resolves as stated... The methods mysql_... They will not be maintained by Php in the future and will then become "decrepated" so the change is advisable... a security problem from version 5.5.X onwards.

  • 1

    then I would like for reasons of Usuability also migrate to PDO this code.

  • 1

    Is this code a legacy, a new system or are you just doing it for learning? It would be very interesting to reformulate your question.

  • 3

    I believe that the security part refers to the use of Prepared statements (which also exists in mysqli, not only in PDO).

  • This is for a new system.

  • the getDB() method can be called via Parent::getDB(); normally, but leaving the method as public would not leave the method open ? @Édipocostarebouças

  • The way you implemented it is already good. The only problem is if you want to use the connection without a table class. I also recommend that you read a little about when to inheritance this link http://www.devmedia.com.br/heranca-versus-compositcao-qual-utilizar/26145.

  • I may be wrong, but the way you implemented it you will create an instance of PDO by table, and I believe your object is to make a Singleton.

  • Right I put the way you passed me within my scope: You recommend me this way or the way you passed me ? : protected $_table; &#xA;&#xA; public function __construct($table)&#xA; {&#xA; $this->_table = $table;&#xA; } Would be the construction of my table from the right bank ? @Édipocostarebouças

  • I would recommend you to do by dependency injection, which would simply pass the PDO instance in the constructor or via a setDb method. The $table parameter would be the table name for you to make the queries select, delete, etc...

  • I’m not getting the _table method out of the class. For example: in index.php I use $table = new base(); $table->_table = "";//Place the name of the database table to insert the data.

  • In the example I gave you it has to be configured in the constructor. if you want to access outside the class, or you let it public or do a get/set methods. if leaving public, change the underscore of the attribute name as this is a standardization for non-public attributes.

Show 9 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.