Is it good to use magic find methods from Doctrine EntityRepository? - php

I'm asking in context of symfony framework.
I am wondering if this is a good practice to use magic find methods (like find($id), findByField($value) etc...).
Those methods neither has return type nor are defined at all. This leads my IDE to mark warnings around them. Also I have to mark type of returned value all the time I use those methods, to make code completion working on those variables.
As a solution I am usually writing getters inside custom repository classes. In symfony docs there is example of such getter, that overload an variant of magic findBy method.
I have a bad feelings about such overloading magic find methods too, because it kind of mixes my own repo implementation with the parent EntityRepository one.
So I end up with writing custom getters that uses "get" prefix instead of "find".
Now, can someone tell me whats the best practice and why ?
EDIT
Recently i was looking for some ways to optimize doctrine, and I have found advise not to use magic finders, so its another argument against magic finders.
I have also read doctrine docs about magic finders and found that:
http://docs.doctrine-project.org/projects/doctrine1/en/latest/en/manual/dql-doctrine-query-language.html#magic-finders
These are very limited magic finders and it is always recommended to expand your queries to be manually written DQL queries. These methods are meant for only quickly accessing single records, no relationships, and are good for prototyping code quickly.
So I have finally worked out my own opinion (and use case) for magic finders. Use them only for speed up coding, and always mark them with TODO, to rewrite them into custom repository methods while cleaning up code.

In my opinion it's a bad practise too. I would suggest you to use findBy([]) and findOneBy([]) methods. I believe when I started learning symfony I had a case when magic methods didn't work at all because properties of my entity was named using underscores.

Related

Is there any drawback with Laravel's use of facades?

There are some criticism [see below] to the Laravel's extensive use of facade, which seems is an anti-pattern, e.g.
Singleton "facades" only upside is that they are relatively "easy to
use", but technical debt introduced from such shortcuts is hard to
even estimate.
Sample code:
$value = Cache::get('key');
So, using the above example code, can anyone show me how this code can be better written in PHP, if we are not using facades?
Disclaimer: I don't necessarily agree that facades are bad or an anti-pattern
A "better" way to do this would be using dependency injection. For example if this is your controller:
public function __construct(\Illuminate\Cache\Repository $cache){
$this->cache = $cache;
}
public function doSomething(){
$value = $this->cache->get('key');
}
Or you can do the same for just one method:
public function doSomething(\Illuminate\Cache\Repository $cache){
$value = $cache->get('key');
}
Note that we're not type hinting the facade class here but the underlying framework class. You can find a list of these classes in the docs.
$app['cache']->get('key');
Do you ever plan on moving your Laravel code-base outside of the Laravel Framework? If not, disregard these comments in my opinion, because that is the only noteworthy disadvantage of Facades.
But if you want to continue down that path, this article has an example that may help you. http://programmingarehard.com/2014/01/11/stop-using-facades.html
I think Laravel does facades right in that they are really just aliases for classes which are actually proxies for resolving the underlying classes from the IoC container. This alleviates most of the problems when trying to test code which may use them. Resolving them from the IoC container yourself is really just doing what Laravel is already doing under the hood while in my opinion sacrificing readability of your code.
In the case of testing, the facades can easily be mocked with Cache::shouldReceive('someFunction')->...
From a design standpoint, you can swap implementations by modifying the service provider so that your implementation is chosen over the default one when resolving from the IoC container using the facade. That should give you the same advantages as dependency injection would give you while maintaining readability of your code.
I think the main issue here is that these aren't facades in their traditional sense and this causes a lot of confusion.
Since you've tagged unit testing, you should keep in mind that static access facades like Laravel's ones make it very hard to accomplish the Isolation principle of unitary tests.
It is impossible (as far as I know) to stub or mock an static-accessed class or method, because you need to be nominative about it.
Another problem you might get is if you need to change the way your application does caching. While you are able to rely solely on Laravel, that's fine, but in the moment you need it to change, you will have to seek for all Cache::get('key') occurrences in order to refactor.
As #lukasgeiter pointed, a better approach would be to use Dependency Injection, through a Dependency Injection Container, such as Pimple.

When should you use singleton pattern and static methods?

When should I use singleton pattern and static (static methods and static properties)?
I have read many blogs/ tutorials/ comments that always say that singleton pattern so I never use it.
But again, there are many php frameworks are using singletons, such as Laravel which is getting more and more popular these days.
For an example, in Laravel,
$app->singleton(
'Illuminate\Contracts\Http\Kernel',
'App\Http\Kernel'
);
$app->singleton(
'Illuminate\Contracts\Console\Kernel',
'App\Console\Kernel'
);
$app->singleton(
'Illuminate\Contracts\Debug\ExceptionHandler',
'App\Exceptions\Handler'
);
If you check it through, you can singleton is heavily used in Laravel (it seems). So what is going on?
Singleton is the first letter in STUPID that we should avoid as far as understand.
But I believe that some programmers will strongly disagree - Its the best way to do it in that situation - if you need to use them, use them. Simple as that.
So, in what situations then you should use singletons if you disagree with STUPID?
Also, in Laravel, you see lots of these,
$users = DB::table('users')->get();
It is either a singleton or a static method I guess (I am not very good at Laravel - just beginning to look into it).
It seems easy to use, but what about in testing, are they going to be difficult to test?
I see this method (DB::something(...)) a lot in other framework as well. They seem not a good idea but many would disagree too I believe. So in what situations you should use static methods then?
I would suggest that the best use of a singleton, which makes practical sense, is when you need to configure a resource that is costly to build.
In most cases, you'll find frameworks tend to create a singleton around database connections. This allows the resource of the database connection to be reused across the framework without having to rebuild the connection with the configurations every query.
The way laravel uses static methods like DB::table is that it will just be a wrapper around the singleton, or as they like to call it, an Inversion of Control Container (http://laravel.com/docs/4.2/ioc). The purpose there is to allow you to have a static interface for which you can change out the back-end singleton provider, should you need to use a different resource.
To answer the last part, the best purpose of a static method, would be either to run some computation over static or constant properties of the class which do not need an instance to exist (consider Java: when to use static methods).

Is it safe to use Doctrine magic "findby" methods for production? Or are they only for prototyping?

I'm using in many places, Doctrine magic methods like below
Doctrine::getTable('User')->findByUserid(id);
Is it recommended to get data like this or should this be replaced with queries?
Also, are there any recommended settings in general when using Doctrine + CodeIgniter?
Yes, if you check the Doctrine source code you will see that it's just a method forwarder. If you prefer you can just replace the magic methods with static ones- but I guess the performance advantage would be negligible.

Drawbacks of static methods in PHP

In a theoretical database access class, I found that there are quite a few helper functions that I use in the class, which have nothing to do the class's instance (and others, that could be manipulated to be unrelated to the class's instance using dependency injection).
For example, I have a function that gets a string between two other strings in a variable. I've been thinking of moving that to a String_Helper class, or something of the sort. This function has already been made static.
Also, I have a function that queries a database, query($sql). The connection details are provided by the instance, but I've been considering making it static, and using query($sql, $connection). Developers would then be able to call it statically and not need to instantiate the database class at all.
For me, the questions are:
Is it worth it to do something like this? Functions like the query function make me wonder if this is not just me trying to make everything as static as possible, without any real need to. Under what circumstances would you consider this useful?
I know static functions are harder to test, but if I make sure that their code is completely dependency free (or uses dependency injection where necessary), then they're just as easy to test as everything else, surely?
It isn't a concern at the moment, but if, in the future, I decided to extend the classes with the static functions, it would be impossible for me to make the current code use my extended functions. I've thought of Singletons, but the same problem arises: the code would be calling Singleton_Class::getInstance(), and not My_Extended_Singleton_Class::getInstance(). Dependency Injection seems to be the only way to solve this issue, but it might lead to a clunkier API, as every dependency has to be given to an object on __construct().
I have a container class, which holds certain pieces of information statically so that they can be accessed anywhere in the script (global scope). If I can't use static functions or singletons, a class that contained instances of different variables would be great. One could use for example Container::$objects['MyClass'] = $MyClass_object;, and then the rest of the code could just access Container::$objects['MyClass']. If I extended the MyClass class, I could use Container::$objects['MyClass'] = $MyExtendedClass_object;, and the code that used Container::$objects['MyClass'] would use MyExtendedClass, rather than MyClass. This is by far the best way to do it, in my opinion, but I'd like to know what you think about it.
Ok, let me answer these one by one...
1. Is it worth doing something like this
Yes and no. Splitting out the helper functions into their own classes is a good idea. It keeps the "scope" of each of the classes rigidly defined, and you don't get creap. However, don't make a method static just because you can. The query method is there to make your life easier by managing the connection, so why would you want to lose that benefit?
2. They are harder to test
They are not harder to test. Static methods that depend on state are harder to test (that access static member variables or global variables). But static methods in general are just as easy to test as instance methods (in fact, they can be easier since you don't need to worry about instantiation).
3. Extending the classes
This is a valid concern. If you put String_Helper::foo() in the class itself, you'll run into issues. But an option would be to set the name of the string helper as a class variable. So you could then do {$this->stringHelper}::foo() (note, PHP 5.3 only). That way to override the class, all you need to do is change the string helper class in that instance. The Lithium framework does this a lot...
4. Global Registry
I would stay away from this. You're basically just making every class a singleton without enforcing it. Testing will be a nightmare since you're now dependent on global scope. Instead, I'd create a registry object and pass it to classes via the constructor (Dependency Injection). You still accomplish the same thing since you have a store for the objects/classes, but you're no longer dependent on a global scope. This makes testing much easier.
In general
When you're looking at doing things like this, I like to stop when I hit questions like this. Stop and sit down and think *What actual problem am I trying to solve?". Enumerate the problem explicitly. Then pull our your supposed solutions and see if they actually solve them. If they do, then think about the future and if those solutions are really maintainable in the long run (Both from a bug fix standpoint, and with respect to feature additions). Only if you're happy with both of those answers should you even consider doing it. Oh, and also remember to keep it simple. Programming is not about making the most complex, most clever or most amazing solution. It's about making the simplest solution that solves the problem...
I hope that helps...
Good Luck!

Should all Front Classes use singleton?

Consider Martin Fowler's Patterns Of Enterprise Application Architecture, and the pattern of Front Controller: http://martinfowler.com/eaaCatalog/frontController.html
Apparently, it uses the singleton pattern. Well, I have a package of classes in php application that work together (like Zend's Controller Package) and there is one class that makes them all usable and since it resembles much of Front Controller's concepts, I named it PackageName_Front. But it shouldn't be a singleton class (as opposed to Front Controller), so do I still let it have the name Front? If not, what do I name it?
Since it's a quite big package, I just need it to follow conventions as much as possible (not in a dogmatic way!) so it would be readable to other developers.
More info: It's not anything related to controllers. It's just an object that works like Zend_Form (which consolidates use of all the other objects like Zend_Form_Element_X and Zend_Validate into one object) But I can't just name it PackageName. It has to be PackageName_Something, and I'm just not sire what Something should be. Maybe "Handler"?... I just wanna make sure when someone reads it's name, doesn't get confused about it's role in the whole Package :)
Apparently, it [FrontController] uses the singleton pattern.
FrontController does not have to be implemented as Singleton. The book does not suggest anything like this. The example in the book uses a Servlet for the Handler.
Just because a class will only be needed once in an application doesnt justify it's implementation as a Singleton. It's missing the purpose of the Singleton which is to enforce a class can only have one instance and provide global access to it. If you need a particular instance only once, consider Just Create One instead.
Many people nowadays (including Erich Gamma of GoF fame) view the Singleton as a code smell and discourage it's use. In a shared-nothing-architecture the Singleton can only restrict instances inside the current request anyway, so the use in PHP is limited. Global access to an object can be achieved without the Singleton pattern, either through the (evil) global keyword or static methods. Global access always creates unneeded coupling. The better way would be to use Dependency Injection, which has the added benefit of providing less coupling and thus better maintainability.
so do I still let it have the name Front? If not, what do I name it? Since it's a quite big package, I just need it to follow conventions as much as possible (not in a dogmatic way!)
There is no such convention about naming classes Front classes to my knowledge. What you describe could be a Facade or a Gateway though. Also, are you sure you cannot name the class after the PackageName? After all, the Zend_Form package has a Zend_Form class, too.
Just from a purely design view, it sounds like you're using that PackageName_Front as a Facade when you say:
there is one class that makes them all
usable
Fowler's implementation of the pattern says:
The Front Controller consolidates all
request handling by channeling
requests through a single handler
object
This insinuates that a Singleton might be used to implement the Front Controller class, but it certainly doesn't constrain it to use it. He doesn't explicitly mention it though.
I don't think it's important whether or not its a Singleton. Just makes sure its the sole channel for requests, and you'll have successfully used the pattern. :)
The idea behind the singleton pattern is to make sure there is only one instance of an object that is supposed to only exist in a single instance. The front controller falls very well into this category, so it would, perhaps, be wise to make it follow a singleton pattern.
If, however, your code will always make sure it calls the constructor only once, then there is room for your non-singleton pattern object.
My 2 cents here, since I'm not any book author or something.

Categories