Active Record

Stefanescu Mihai 7 months ago Design Patterns

Design pattern-ul Active Record este un design pattern des intalnit in programarea orientata pe obiecte pentru crearea, citirea, modificarea si stergerea datelor din baza de date.

In acest pattern, fiecare inregistrare din baza de date este reprezentata de un obiect, iar metodele de pe acest obiect sunt folosite la executarea actiunilor de pe inregistrare. Acest pattern ofera un mod mai intuitiv de a interactiona cu baza de date.

Hai sa vedem cum functioneaza acest pattern in practica.

Prima data trebuie sa ne definim o clasa ce reprezinta o inregistrare din baza de date. Aceasta clasa trebuie sa aiba ca si proprietati coloanele din tabela dorita si metodele cu care sa faca actiunile dorite pe acele proprietati.

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

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

    public function save() {
        // aici va fi salvarea in baza de date
    }

    public function delete() {
        // aici va fi stergerea din baza de date
    }

    // atat timp cat ave proprietati private trebuie sa avem si getteri/setteri pentru ele
}

Pentru a interactiona cu baza de date avem nevoie de o instanta a obiectului, de exemplu pentru a crea un nou user putem face:

$user = new User(1,'mihai','[email protected]');
$user->save()

Sau pentru a cauta un anumit user ceva de genul:

$user = new User();
$user->findBy(['email' => $email]);

Zic ceva de genul, pentru ca aici am vazut mai multe abordari, cum ar fi si

$user = User::findBy(['email' => $email]);

Modul de implementare tine de fiecare persoana, cum crede ca este mai ok pentru proiectul respectiv.

Folosind acest design pattern, Active Record encapsulezi operatiile cu baza de date in obiecte, facandu-ti codul mai intuitiv si usor de inteles. In Unele cazuri chiar iti poate simplifica codul, facandu-l mai usor de intretinut. Totusi, este foarte important de mentionat ca acest design pattern poate duce la cod foarte dependent de baza de date (tight coupled) facand dificila o schimbare de schema fara a schimba si codul.

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

Ilse # 5 months ago Hello would you mind sharing which blog platform you're working with? I'm looking to start my own blog in the near future but I'm having a difficult time selecting between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your design seems different then most blogs and I'm looking for something unique. P.S Sorry for being off-topic but I had to ask!
online aankoop van moxipin in Spanje # 1 month ago Remarkable! Its actually awesome paragraph, I have got much clear idea concerning from this paragraph.
prijzen van butenafine # 1 month ago I was wondering if you ever considered changing the layout of your website? 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 1 or two images. Maybe you could space it out better?
furadantine-Kauf in Deutschland # 1 month ago This information is worth everyone's attention. How can I find out more?
ou acheter du farlutal sans ordonnance à Paris # 3 weeks ago I am not certain the place you are getting your info, but good topic. I must spend some time learning more or working out more. Thanks for fantastic info I used to be on the lookout for this information for my mission.
Margie # 3 weeks ago continuously i used to read smaller posts which as well clear their motive, and that is also happening with this paragraph which I am reading at this place.
Charli # 3 weeks ago Hi there, all is going sound here and ofcourse every one is sharing data, that's truly excellent, keep up writing.
Harriett # 3 weeks ago An impressive share! I have just forwarded this onto a colleague who was conducting a little research on this. And he actually ordered me lunch simply because I stumbled upon it for him... lol. So allow me to reword this.... Thanks for the meal!! But yeah, thanx for spending time to discuss this issue here on your site.
Ernie # 2 weeks ago Wow that was unusual. I just wrote an incredibly long comment but after I clicked submit my comment didn't show up. Grrrr... well I'm not writing all that over again. Anyway, just wanted to say superb blog!
acyclovir sans ordonnance # 2 weeks ago Why people still use to read news papers when in this technological globe the whole thing is presented on net?
prix du allegra au Maroc # 2 weeks ago It's the best time to make some plans for the long run and it is time to be happy. I've learn this submit and if I may I want to suggest you few fascinating things or advice. Perhaps you can write subsequent articles regarding this article. I desire to read even more issues approximately it!
vermox ohne Rezept in Zürich # 1 week ago Hi, I desire to subscribe for this webpage to take newest updates, therefore where can i do it please help out.
nolvadex zu erschwinglichem Preis in Deutschland # 1 week ago Hi, Neat post. There's a problem together with your web site in internet explorer, might check this? IE nonetheless is the market leader and a huge component to other people will miss your wonderful writing because of this problem.
aankoop van etodolac in Spanje # 1 week ago If you want to increase your knowledge just keep visiting this website and be updated with the most up-to-date news update posted here.
commander ivermectin en Belgique en ligne # 6 days ago Thanks in support of sharing such a pleasant opinion, article is fastidious, thats why i have read it fully
cefuroxime recommandé par les spécialistes # 5 days ago Everyone loves it when folks get together and share thoughts. Great blog, keep it up!
aldara kopen in Italië # 4 days ago Why people still use to read news papers when in this technological world all is available on web?
kan men berodual zonder recept krijgen in België # 3 days ago You can definitely see your enthusiasm within the article you write. The world hopes for more passionate writers like you who are not afraid to say how they believe. Always go after your heart.
Cierra # 2 days ago Pretty nice post. I just stumbled upon your blog and wanted to say that I've really enjoyed surfing around your blog posts. After all I'll be subscribing to your rss feed and I hope you write again soon!
filartros sans risques pour la santé # 5 hours ago Keep on working, great job!
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.