I'm looking in to using NotORM for a project (no code has been written yet).
I get that NotORM can make an object based on MySQL tables. What I don't quite understand is how I use it if I have an existing class in place. Should I inject NotORM in to the class? But then how do I use it to load/save from the db?
I guess the main problem I am trying to understand is if I have a class that I save to the db over multiple tables (let's call it MyClass), I understand why an ORM is a good idea, as the class may be stored over multiple tables in the db, but what if MyClass has some methods that do other stuff (for example maybe it talks to an external api elsewhere)? Just loading straight from the db using NotORM is not going to make the same 'MyClass' - from what I understand it will only have the data from the db.
Related
Hey Guys
I know Stackoverflow is may not the right place to ask, if there's another Stackexchange group where
this question fits better, then please tell me.
So, I'm trying to learn OOP. I think I understand it quite good, but there's one thing I really can't figure
out what the right way is, and thats the handling of database.
So, I'm confused a bit of what should go in which class.
Lets say I've a db class. Inside of this class I'm connecting to the database in a constructor. And now lets say
I've got a user class.
So now the question:
Where should I put in the query for example creating a new user? Should i create a method in the user class,
or should I create a method in the DB class? If in DB class, should it really be a method like create_user()
or should it more be something globally like query where I can pass in whatever query I want.
Here, for example a project from Github:
https://github.com/christran/PHP-OOP-Login-Register-System/blob/master/classes/user.php
As you can see, all query methods are in db.php and from user.php he's just calling this methods. So is this the right way to go?
Or doesn't it matter at all? May, any of those approches is "more" OOP than the other?
It's actually just really confusing me and I don't understand whats the better way. I've searched a lot, but never
found an article to this specific question.
So what I did, I looked for projects on Github and looked at their code, how they've solved the problem...
But with this method I just got confused even more, because you see both.
Is it just a preference of the coder?
I am really thankful for all your help. Have a nice day! :)
Here a little example of what I mean:
Query inside user class:
class user {
private function createUser() {
//SQL Query here (prepared statements etc...)
}
}
OR:
class user {
private function createUser() {
// Call to db.class to insert_method() ...
}
}
Basically, you are looking into ORM.
To answer your question specifically,
Should i create a method in the user class
This is possible, and is called Active record pattern, where an entity contains not only methods related to itself (like $user->getBirthday()) but also methods that related to database interaction (like $user->save()).
or should I create a method in the DB class?
This is impossible, as this class will become enormously big.
However, you can create a sister class for the every entity, that will be responsible for the database interaction. This approach is called Data Mapper pattern. For example, there is a User class that contains methods related to the user, and also a UserMapper class, that is inherited from abstract mapper class with generic methods $userMapper->save(), $userMapper->find() and such.
The createUser method that contains the query shouldn't be part of the User object, but neither of the database object. The first one is for business logic. The latter one is for managing the database method and providing generic functionality for executing statements. A different object inbetween those objects should be the one that takes the data from the user object and generate the queries for storing it in the database.
The term I think you're looking for here is ORM (Object-relational mapping).
This concept is about mapping objects to a different, incompatible structure, like a database.
There are ORM libraries/frameworks available for PHP which can do much of the work for you, and some of them are part of, or can be used with, popular MVC frameworks like Eloquent ORM in Laravel. For example, they will often provide the basic CRUD operations by implementing the SQL statements needed after you just configure the right database table.
In terms of OOP, you will often have an extra layer on top of it. So you got a business object User, which contains the rules for users, for instance rules it has to follow for a user name. The business object will enforce those rules and contain the general behaviour of a User object. For saving you make use of an ORM to save a user object to a specific database. The database logic is not in the User object itself. It shouldn't have to know about the specific queries to save itself, and maybe it shouldn't even be aware of concepts like loading and saving. It just contains logic and data, and other parts of the implementation are responsible for persisting that data (optionally using an ORM framework to make things easier).
i'm new to php and codeigniter but i have experience with pylons and sqlalchemy.
there you define model classes and then you use command something like "paster setup-app development.ini" and (paster?) creates tables for you and you dont have to write any sql code...
i was trying this with codeigniter and datamapper but so far i'm not sure if it is possible. so here i am asking you if it is possible?
i am very confused because in "models/" you can put your own classes (like in sqlalchemy). in these classes you define every attribute, relationship and other stuff. so why would you need to write the same thing 2 times? (1st in this class 2nd in sql script)
That is not possible, Datamapper implements the Active Record pattern which expects the tables to be there.
There is no need to define any attributes in a Datamapper model, it will be fetched from the associated table (and cached).
I'm currently working on a Shopping Cart in which I use a custom Mysql Class to send query to the db.
On this project, I plan to extends this Mysql Class for each Object that I will use : Category, Product, Shopping Cart.
If I create a class like this one:
class Catalog_Categories extends Mysql{}
And then another one like this:
class Catalog_Products extends Mysql{}
Are those classes using the same Mysql Object to connect on DB or are they using 2 separate connections?
I'm a little bit lost.
Thanks!
Carl.
That depends on how your Mysql class is written. If you write it using a Singleton pattern, it will maintain one database instance. You could write it as a Factory pattern and have it generate a new instance for each object that uses it. There are many other patterns and possibilities available so it all just depends on how you want it to work and how you wrote the custom Mysql class.
Assuming that you are creating a database connection in your Mysql class, every object your create of any of the extending classes, will create a new DB connection.
There are several ways to avoid this, for example, you can create one global connection to your database and pass that connection to the constructor of your class so that they all will use that same connection.
Are those classes using the same Mysql Object to connect on DB or are they using 2 separate connections?
We cannot answer this question until we see the complete code.
But extending in this case looks like a bad idea. If you cannot say that class A is a class B - then you should prefer composition over inheritance. This means that Catalog_Products should have a reference to mysql object, but shouldn't extend it.
To get you idea when inheritance is justified is class mysql extends database. In this case you can say "mysql is a database", so extension here looks reasonable as long as database class encapsulates the common logic, and mysql class represents more detailed specifics.
I am not sure what I'm doing is called ORM or Active Record Pattern.
I have an Entity base class that entities/database tables will inherit. These classes will have methods like
find
findBy
findAllBy
insert
update
delete
Getters & Setters for column data (eg. name, title, etc) via magic methods
Problem now is how do I create a database connection?
Dependency Injection - sounds complicated ...
Use a global variable, that these classes will expect to be set? - Doesnt sound right
Have a base class that Entity inherit that contain all database connection info? - doesnt sound right either
Maybe I am doing it wrong? I am open to any ideas, preferably simple for a start. I am wanting to create a simple framework for a start (not using Doctrine for example), it will give me a foundation on how such framework works. Also if its a small project, using a big framework may over-complicates things
There isnt really much thats simple about what youre attempting. Its complex thing :-)
You need to have some kind of basic entity manager and/or table class which usually holds the reference to the DB connection (or some sort of object that wraps it). All the Entity's then pass themselves to the manager when their save or delete methods are called and the manager will work out the query needed to modify the db.
You can either inject this manager, or make it a singleton and have your classes fetch it when instantiated for example.
If i were you i would check out PHP Objects Patterns and Practices by Matt Zandstra. It goes into all these patterns with some basic implementation examples.
I am searching for a database abstraction layer in future PHP projects. Until now I have worked with plain SQL-commands and arrays on the one hand fully featured ORMs like Doctrine on the other hand.
I don't like ORM because most of the time the job is to get a list of data from the database and to send it to the template engine. Both work fully fine with arrays and there's no need to make it all complicated by capsule the data in an object when the template just needs the plain array. I don't like the plain-SQL approach either because for the simple CRUD stuff I have to write everything myself and also I don't like to maintain two models of my data (one in the DB and the other within my database access object).
Is there something which let's me define the model one time only and generates the elementary stuff for me (like in Doctrine) but which saves me from the active record pattern?
The db is not a model, its the raw data source, and the model is, in thoery, more than just the data fields, it should also be the methods that affect the model's data.
You are always going to have to tell the program what to insert and where into the db, even if you use a library that encapsulates the sql or if you write it yourself.
If you find yourself writing the similar "insert" and "select" commands over and over, then its time to design some functions or classes.