I've seen projects where the classes in the DB layer have just static functions in them and other projects where those classes need to be instantiated to get access to the member functions.
Which is "better" and why?
I like a single object to be correlated to a single record in the database, i.e. an object must be instantiated. This is your basic ActiveRecord pattern. In my experience, the one-object-to-one-row approach creates a much more fluid and literate presentation in code. Also, I like to treat objects as records and the class as the table. For example to change the name of a record I do:
objPerson = new Person(id)
objPerson.name = "George"
objPerson.save()
while to get all people who live in Louisiana I might do
aryPeople = Person::getPeopleFromState("LA")
There are plenty of criticisms of Active Record. You can especially run into problems where you are querying the database for each record or your classes are tightly coupled to your database, creating inflexibility in both. In that case you can move up a level and go with something like DataMapper.
Many of the modern frameworks and ORM's are aware of some of these drawbacks and provide solutions for them. Do a little research and you will start to see that this is a problem that has a number of solutions and it all depend on your needs.
It's all about the purpose of the DB Layer.
If you use an instance to access the DB layer, you are allowing multiple versions of that class to exist. This is desirable if you want to use the same DB layer to access multiple databases for example.
So you might have something like this:
DbController acrhive = new DbController("dev");
DbController prod = new DbController("prod");
Which allows you to use multiple instances of the same class to access different databases.
Conversely you might want to allow only one database to be used within your application at a time. If you want to do this then you could look at using a static class for this purpose.
As lomaxx mentioned, it's all about the purpose of the DB model.
I find it best to use static classes, as I usually only want one instance of my DAL classes being created. I'd rather use static methods than deal with the overhead of potentially creating multiple instances of my DAL classes where only 1 should exist that can be queried multiple times.
I would say that it depends on what you want the "DB layer" to do...
If you have general routines for executing a stored procedure, or sql statement, that return a dataset, then using static methods would make more sense to me, since you don't need a permanent reference to an object that created the dataset for you.
I'd use a static method as well if I created a DB Layer that returned a strongly-typed class or collection as its result.
If on the other hand you want to create an instance of a class, using a given parameter like an ID (see #barret-conrad's answer), to connect to the DB and get the necessary record, then you'd probably not want to use a static method on the class. But even then I'd say you'd probably have some sort of DB Helper class that DID have static methods that your other class was relying on.
Another "it depends". However, I can also think of a very common scenario where static just won't work. If you have a web site that gets a decent amount of traffic, and you have a static database layer with a shared connection, you could be in trouble. In ASP.Net, there is one instance of your application created by default, and so if you have a static database layer you may only get one connection to the database for everyone who uses your web site.
It depends which model you subscribe to. ORM (Object Relational Model) or Interface Model. ORM is very popular right now because of frameworks like nhibernate, LINQ to SQL, Entity Framework, and many others. The ORM lets you customize some business constraints around your object model and pass it around with out actually knowing how it should be committed to the database. Everything related to inserting, updating, and deleting happens in the object and doesn't really have to worry the developer too much.
The Interface Model like the Enterprise Data Pattern made popular by Microsoft, requires you to know what state your object is in and how it should be handled. It also requires you to create the necessary SQL to perform the actions.
I would say go with ORM.
Related
on laravel we can access by using DB::table('table')->get(); or using model::('table')->all();
My question is what's the difference between them ?
thanks.
You can do this because Model and the DB facade both implement functions that yield a Builder instance.
https://laravel.com/api/5.2/Illuminate/Database/Eloquent/Model.html
https://laravel.com/api/5.2/Illuminate/Database/Query/Builder.html
The difference is, instances of Model have properties which set up a Builder with predesignated information, like table, and also provide it with events, relationship information, specific static bindings, and a bunch of other handy helpers that constrain to objects and make object-oriented programming easier.
So yes, you can use a model and then take the query Builder object and change its table (just like you can change anything else about a Builder), but it's fighting a system specifically designed to make query building easier.
At heart, what Laravel does is take the Symfony2 framework and streamline it so everything is simpler. Models are one such instance of this.
I am learning some patterns, Unity of work / repository... There are some examples on web, but no one connects to more than one database.
In my applications almost always I have the need to get some object from a database (for example users) and some other object from another, how can I use the patterns ? (Since I am a novice on this subject an explicit example is a must)
Thank you!
As a general reference I advise you and anyone interested to visit http://martinfowler.com/eaaCatalog/index.html
which has a collection of UML and explanation over the most common Design Pattern for enterprises software
In your specific case Unity of work is particularly suited to work along with Data Mapper and Identity Map. I guess to understand 100% unity of work one must master also the other 2 pattern.
To answer your question I think you can create a unity of work and save it in a registry, so it is available all over the application. The unity must be a singleton since you need to ensure a central gateway to communicate with the database. Inside your unity of work you will have an identity map which is a collection of valued Objects in memory representing your model which is responsible to maintain the object states during all the application's operations. The unity will be used by your service layer to perform CRUD operations over the model and commit these changes.
To work with more databases I guess you need to leverage some sort of namespaced access to the object stored in the Identity map. You have the choice where to namespace: unity of work or identity map. The decision is really up to your application and use cases. You might need to connect to different DBs for splitting responsibilities between read and write or trying to integrate heterogeneous data sources.
An alternative would be to inject the DB object into the unity of work methods, in this case the application has 100% control over which database is used.
The repository pattern as far as I understand helps you to abstract to the storage of you model and it is particularly useful when you are working with heterogeneous data sources of you must provide such a flexibility to your application. Therefore I guess it is quite different from unity of work and Data Mapper layer.
I created for a project a single class, that contains all access code to the database.
Is this a good practice , under the assumption that this class doesn't contain any logic, or should i use several classes? If yes, how should i partition my code? I use C# .Net.
Actually Under the concept of MVC framework, it is a good practice to create a different class for database access, seperate class for logic and seperate class for your views.
You are doing good if you are writing a seperate class for database access under the assumption that it does not contain any logic.
In Agile Developement there is a term named as Database Encapsulation Layers.
A database encapsulation layer hides the implementation details of your database, including their physical schemas, from your business code. In effect this layer provides your business objects with persistence services – the ability to read data from, write data to, and delete data from – data sources. Ideally your business objects should know nothing about how they are persisted, it just happens. Database encapsulation layers aren’t magic and they aren’t academic theories; database encapsulation layers are commonly used practice by both large and small applications as well as in both simple and complex applications. Database encapsulation layers are an important technique that every agile software developer should be aware of and be prepared to use.
An effective database encapsulation layer will provide several benefits:
-> It reduces the coupling between your object schema and your data schema, increasing your ability to evolve either one.
-> It implements all database-related code in one place.
-> It simplifies the job of application programmers.
-> It allows application programmers to focus on the business problem and Agile DBA(s) can focus on the database.
-> It gives you a common place to implement data-oriented business rules and logic.
-> It takes advantage of specific database features, increasing application performance.
Hope this helps.
If your database is quite small, say, only a couple of tables, you could write all your queries in one class. otherwise I would suggest that per Entity/Table one class. for example, StudentDao.class will only focus on the queries to database table "STUDENT", and TeacherDao.class will only contain queries to table "TEACHER". if you are gonna implement a complex business logic, you may want to have a service class, to weave StudentDao and TeacherDao together.
Unless your data access is very simple, probably not.
you probably shouldn't need to write this code yourself. Take a look at some Object Relational Mapping tools. NHibernate is a popular .Net solution. http://en.wikipedia.org/wiki/NHibernate
If you really do want to write it yourself look up design patterns in this area, like the Data Transfer Object pattern. http://martinfowler.com/eaaCatalog/dataTransferObject.html
These are some of the suggestions while accessing database.
1.) Always keep your database access parameters in a properties file. Use a handler to get those data. Because when you change your database then you need not change your code just make a change in the properties file it's enough.
-- So here you need a handler class.
2.) Never create a single class (a god class) which performs all the actions. Disperse your behaviour in to different classes depending on the intent. For example Keep all read behavior in one class, Write behavior in another class ... so on.
3.) You can create a class which deals with connection creations and pooling stuff...
Hope this helps.
I have several objects, like products, order, etc. When I get information from my database I take a row and create one of the types of objects. I then work with that object created. I read this is called a factory.
Is there some advantage to doing this? Especially in a loosely typed language like PHP?
Thanks
edit: is this where I get database agnosticity? Is this what an ORM essentially does?
By creating your objects from the database queries, you are defining the mapping between your objects and the relational database. This is exactly what ORM software does.
By doing so and ensuring that your objects never directly access the database, but instead use your database-access functions/objects, you are protecting your code from changes in two ways:
Changes to your database schema will not ripple through your code. Instead, the code changes will be located only in your database access objects.
You can switch to a different DBMS by implementing a new database layer that follows the same interface as the original. Your other objects will not require changes.
I guess in that sense, you gain some database-agnosticity, but you'll probably be better off using a database library that provides that agnosticity out of the box.
In my opinion, the advantage is you are working with objects and gain all of the advantages that an object-oriented language offers. You can then read the domain logic at a higher level (in terms of the objects you have defined) without sifting through database queries. Writing the ORM yourself can be tough, but there are tools out there that help with that.
This is the route I normally take, but I don't do any PHP development, so I can't say how well it applies to that language.
What you're describing is an implementation of a Data Access Layer - it doesn't sound like an example of the Factory Method pattern, nor the Abstract Factory pattern.
Yes, ORMs bridge the gap from objects to relational databases, and can serve as your Data Access Layer. Bear in mind, any ORM you use has certain pros/cons/limitations. Depending on your experience and requirements, writing your own data access layer is sometimes a good idea; don't feel like you HAVE to use a 3rd-party ORM.
Yes, a good data access layer makes it easy to swap out your storage mechanism (different database, XML, flat files, whatever) without changing your business logic, UI, or other code.
Regardless of loose-typed or strong-typed languages, if you're working in an OO language, it will be much easier to write code using data objects (provided by an ORM or homegrown data access layer). I'm sure it's possible to write a system with no data access layer, where your business layer works directly with the database. But it will likely be more challenging to implement and maintain.
I maintain an application which has many domain entities that draw data from more than one database. The way this normally works is that the entities are loaded from Database A (in which most of their fields are stored). when a property corresponding to data in Database B is called, the entity fires off SQL to Database B to get all the relevant data.
I'm currently using a 'roll-your-own' ORM, which is ugly, but effective (and easy to understand). I've recently started using NHibernate for entities drawn solely from Database A, but I'm wondering how I might use NHibernate for entities drawn from both Databases A and B.
The best way I can think of do this is as follows. I continue to use a NHibernate-based class library for entities in Database A. Those entities which also need data from Database B expose all their data from Database B in a single class accessed via a property. When this property is called, it invokes the appropriate repository, and the object is returned. The class library for accessing Database B would therefore need to be referenced from the class library for accessing Database A.
Does this make any sense, and is there a more established pattern for this situation (which must be fairly common).
Thanks
David
I don't know how well it maps to your situation, or how mature the NHibernate porting for it is at this point, but you might want to look into Shards.
If it doesn't work for you as-is, it might at least supply some interesting patterns to consider.
EDIT (based on comments):
This indeed doesn't seem to map to your situation, as Shards is about horizontal splitting of data.
If you need to split vertically, you'll probably need to define multiple persistence units. Queries and transactions involving both databases will probably get interesting. I'm afraid I can't really help much with this. This question is definitely related though.