简体   繁体   中英

What does this mean “PDO provides a data-access abstraction layer” and “PDO does not provide a database abstraction”?

I am new to PHP and decided to start learning PDO but one thing that is confusing me a lot that is: PDO provides a data-access abstraction layer and PDO does not provide a database abstraction

What does it means ?

Reference link

Can anyone tell ?

Thanks !!!

PDO provides a data-access abstraction layer: PDO can abstract the "database driver" (eg MySQL, PostgreSQL etc...).

PDO does not provide a database abstraction: PDO cannot abstract SQL statements.

Example

This SQL works with MySQL but not with PostgreSQL.

// MySQL connection
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password, $options);

$sql = "REPLACE INTO blog (uuid, title) VALUES (:uuid, :title)";
$pdo->prepare($sql)->execute(['uuid' => '1234', 'title' => 'test']);

// PostgreSQL connection
$pdo2 = new PDO("pgsql:host=$host;dbname=$dbname", $username, $password, $options);

// This should fail
$pdo2->prepare($sql)->execute(['uuid' => '1234', 'title' => 'test']);

PS: PDO does not provide a "real" data-access abstraction layer.

For example the PDO object has a lastInsertId() function. For SQLite and MySQL you can just call it as such:

$id = $pdo->lastInsertId();

However, PostgreSQL requires an explicit sequence identifier. By default this follows the format tablename_idfield_seq, so we might specifiy as this:

$id = $pdo->lastInsertId('articles_id_seq');

Luckily the parameter gets ignored by SQLite and MySQL, so we can just specify it all the time.

Simply put, data-access abstraction refers to how PDO interacts on your behalf with a given database . Generally speaking, all the nitty-gritty details such as connection specific properties, security, transactions etc. are implemented for you in a standard manner. All you need to do is learn how PDO implements these and then you can start using MySQL, MSSQL, Oracle, Postgres.

That being said, it doesn't write the actual SQL/DML for you. You still need to physically type that in. Which bring us to the 2nd point, database abstraction . This refers to hiding the low-level SQL/DML needed to perform queries. If you've ever worked with an ORM then you'll be familiar with this concept. Instead of writing

$query = 'SELECT * FROM ...'

you'd write

$db->get(Person, $id)

In summary, with PDO you get:

  • connections, security, error handling, and other data access abstractions

You don't get:

  • SQL/DML written behind the scenes for you like you would with an ORM

Take a peek at https://phpdelusions.net/pdo for a better understanding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM