Design pattern-ul Data mapper explicat in PHP

Stefanescu Mihai 7 months ago Design Patterns

Design pattern-ul Data Mapper este un design folosit pentru a separa in 2 niveluri datele si logica de business a aplicatiei. Acest pattern este des folosit in sistemele de tip object relational mapping (ORM).

In acest pattern, datele sunt transferate intre obiecte in aplicatie, tinandu-se pe obiecte separate datele de logica de business (vezi active record, unde un model putea avea atat date cat si logica de business). Facand aceasta separare ne putem pastra obiectele ce se ocupa de date fara logica, iar obiectele de logica doar cu logica, facandu-le mai usor de modificat, intretinut si testat.

Hai sa discutam de un exemplu practic despre cum functioneaza acest pattern.

Prima data trebuie sa definim un obiect ce reprezinta datele stocate in baza de date. Acest obiect va avea proprietati ce corespund campurilor din tabela dorita, dar nu va contine nicio bucata de logica (vezi save/find/update/delete de pe un model din pattern-ul Active Record)

class User {
    private $id;
    private $username;
    private $email;

    public function __construct($id, $username, $email) {
        $this->id = $id;
        $this->username = $username;
        $this->email = $email;

    // Getteri si setteri pentru proprietati

Acum, avem nevoie de un obiect de tip data mapper  ce se va ocupa de logica de access a datelor. Acest obiect va avea metode pentru crearea, selectarea, modificarea si stergerea datelor din baza de date.

class UserMapper {
    private $pdo;

    public function __construct($pdo) {
        $this->pdo = $pdo;

    public function find($id) {
        // codul pentru a efectua un select dupa id

    public function save(User $user) {
        // codul pentru a salva un obiect in baza de date

    public function delete(User $user) {
        // codul pentru a sterge un obiect din baza de date

Acum, putem folosi obiectul de tip mapper pentru a interactiona cu baza de date.

$pdo = new PDO('mysql:host=localhost;dbname=invata_programare', 'user', 'password');
$userMapper = new UserMapper($pdo);

$user = $userMapper->find(1);
$user->username = 'm105';

Folosind acest design pattern, data mapper, poti mentine la nivele separate logica de business de datele din baza de date,facand codul mai usor de inteles, intretinut si testat. Pe langa acest aspect, ar trebui sa avem in vedere si ca putem encapsula cod specific pentru ubaza de date astfel facnd mai usor schimbarea de la un sistem de baze de date, daca este nevoie.

Programator de ~8 ani, am lucrat la proiecte din mai multe industrstrii, de la eCommerce la telecomunicatii la automatizari. In acest timp am folosi diferite tehnologii, de la PHP, MySQL, PostgreSql, RabbitMq, Redis, Memcached si altele.

Get in touch
Pentru nelamuriri, dubii, comentarii si chestii de pe suflet ne putem auzi pe Discord, Reddit sau poti deschide o discutie noua pe forum

affiliate programs for vitamins and minerals # 6 months ago social media management jobs for remote income work-life balance online jobs for stay at home moms best health affiliate programs
ways for doctors to make additional income # 6 months ago medical doctors and passive income best online business ideas for doctors realistic ways for students to earn money from home make money as a therapist
Cheapest place to get Farxiga # 5 months ago Buy diabetes medication online with delivery Insulin without a prescription Where to buy affordable illegal diabetes medications online? Give me the best deals on diabetes meds online. no prescription required!
Neck pain relief # 5 months ago Hey there, You have done a great job. I'll definitely digg it and personally recommend to my friends. I am sure they will be benefited from this web site.
Are you spending money on Robux # 5 months ago I'm now not certain where you're getting your information, however good topic. I needs to spend a while learning more or working out more. Thank you for magnificent info I was on the lookout for this information for my mission.
reviews of natural anxiety remedies in mackay # 5 months ago Hello my friend! I wish to say that this article is awesome, great written and include approximately all vital infos. I'd like to look extra posts like this .
Cedric # 2 months ago Thanks for some other informative site. The place else may just I get that type of info written in such an ideal approach? I've a mission that I'm just now running on, and I have been on the glance out for such information.
precio de theophylline con receta # 1 month ago Thanks , I have recently been looking for info approximately this subject for a while and yours is the greatest I've found out so far. However, what in regards to the conclusion? Are you sure concerning the supply?
¿dónde comprar cymbalta 30 sin prescripción médica? # 1 month ago You can definitely see your skills in the article you write. The sector hopes for more passionate writers such as you who are not afraid to mention how they believe. Always follow your heart.
comprar triamcinolone 4 mg en línea en Bogotá # 1 month ago It's fantastic that you are getting ideas from this post as well as from our dialogue made at this place.
astonin om te kopen in Frankrijk # 1 month ago You've made some good points there. I checked on the web for additional information about the issue and found most people will go along with your views on this website.
obtenir du sildenafil sans ordonnance en Suisse # 1 month ago My brother recommended I might like this blog. He was totally right. This post truly made my day. You can not imagine simply how much time I had spent for this info! Thanks!
Xlpnuw # 1 month ago tricor price <a href="">buy fenofibrate 200mg generic</a> tricor buy online
donde comprar ciprofloxacine en Bolivia # 1 month ago Hey very interesting blog!
procardia online beschikbaar zonder recept # 1 month ago There is certainly a lot to find out about this issue. I love all the points you made.
Qvtwcd # 1 month ago order generic ketotifen <a href="">buy zaditor 1 mg generic</a> imipramine pills
Sjfllp # 1 month ago buy mintop for sale <a href="">ed pills cheap</a> ed pills no prescription
Lvidwt # 4 weeks ago precose pills <a href="">precose order online</a> buy fulvicin 250 mg sale
oxiderma en venta en Buenos Aires sin prescripción # 4 weeks ago Somebody essentially help to make seriously posts I might state. This is the very first time I frequented your web page and to this point? I surprised with the research you made to make this actual publish extraordinary. Excellent activity!
Ajttxn # 4 weeks ago order aspirin 75 mg for sale <a href="">order zovirax online</a> imiquimod brand
Orval # 3 weeks ago You could definitely see your enthusiasm in the article you write. The world hopes for even more passionate writers such as you who are not afraid to mention how they believe. All the time go after your heart.
Jodi # 3 weeks ago you're in point of fact a good webmaster. The site loading pace is incredible. It kind of feels that you are doing any unique trick. Also, The contents are masterwork. you've done a excellent task on this topic!
Jdvldv # 3 weeks ago buy generic duphaston <a href="">buy dydrogesterone 10 mg pills</a> empagliflozin 25mg us
Fgucgp # 3 weeks ago order generic fludrocortisone 100 mcg <a href="">rabeprazole 20mg without prescription</a> imodium online
Mlpnav # 2 weeks ago generic monograph 600 mg <a href="">etodolac over the counter</a> cilostazol uk
Fqpftt # 2 weeks ago buy prasugrel 10 mg generic <a href="">thorazine for sale</a> detrol sale
curretab mit ärztlicher Verschreibung # 2 weeks ago As the admin of this site is working, no question very rapidly it will be renowned, due to its quality contents.
Online-Kauf von Medikamenten # 2 weeks ago This piece of writing is in fact a fastidious one it helps new web users, who are wishing in favor of blogging.
Syrqah # 2 weeks ago buy ferrous sulfate 100 mg for sale <a href="">buy generic ferrous sulfate 100 mg</a> buy sotalol online cheap
Dljfxl # 2 weeks ago how to get pyridostigmine without a prescription <a href="">buy mestinon sale</a> buy rizatriptan 10mg for sale
Jzxnqi # 1 week ago order enalapril 10mg generic <a href="">lactulose order online</a> purchase lactulose
Kann man emsam ohne Rezept in Brüssel bekommen? # 1 week ago bookmarked!!, I love your web site!
Rqvycz # 1 week ago buy latanoprost sale <a href="">buy rivastigmine 3mg pills</a> buy rivastigmine 6mg for sale
Infórmate sobre el precio del aventyl bajo receta médica en Chile # 1 week ago Nice weblog right here! Also your website lots up very fast! What web host are you the use of? Can I am getting your affiliate link on your host? I want my site loaded up as fast as yours lol
Yjlwju # 6 days ago order micardis for sale <a href="">movfor pills</a> movfor order online
Tmyiyg # 4 days ago cenforce drug <a href="">cost cenforce 100mg</a> order generic chloroquine
Pdodbg # 2 days ago buy modafinil 200mg online <a href="">buy deltasone 10mg for sale</a> brand deltasone 5mg
etoricoxib sin prescripción # 1 day ago I was curious if you ever thought of changing the page layout of your site? Its very well written; I love what youve got to say. But maybe you could a little more in the way of content so people could connect with it better. Youve got an awful lot of text for only having one or 2 images. Maybe you could space it out better?
Club-ul este dedicat membrilor si ofera access la mai multe zone ale website-ului.
Login Register

🔖 Bookmarks
✨ Pentru a sustine aceasta comunitate am sa te rog sa te autentifici sau sa te inregistrezi!

🌪️ Discord
Back to top
Folosim cookie-uri pentru a oferi functionalitatile critice ale aplicatiei Invata-Programare. Folosim cookie-uri si pentru a analiza traficul, pentru care e nevoie de consimtamantul dvs. explicit.