I can't find how to make something like ::getInstance() like in other php frameworks to get Application (singleton) instance in symfony2
I found only sfContext::getInstance() buy it doesn't work and looks like its method from symfony1
add more info.
I have some class - abstract class Post { }. I want to get some application config, environment variables inside this class. i don't want to put all this stuff to constructor method, instead i want to call application instance and get all i want
If you take a look at web/app.php you will see that your application instance is just a global variable called kernel
$kernel = $GLOBALS['kernel'];
die(get_class($kernel));
However, the reason #san40 told you to read the documents is that you probably never actually need it for anything. SF2 is very different than SF1. So if you explained why your wanted the instance then someone might be able to suggest alternative approaches.
===================================
Looking at web/console shows that same principle for console commands except the instance is called application.
die(get_class($GLOBALS['application']))
However, using the application instance to pull environment variables and such is not recommended. If nothing else, it makes your objects completely dependent in the instance. Dependency injection is what you want. Read through the stuff in the s2 documentation.
Related
I have read a lot of SO topics about this already, but still haven't found (or have been able to create) a proper answer.
I am working on a small MVC framework and I want some global class/object that I can call from my controllers (but maybe models too).
There are a couple of routes I can take:
Global variable
Static class/Registry
Dependency injection
The internet seems to agree that the DI is the best route to take. I think I have grasped the idea, but am not comfortable yet. So I want to throw in some background information; I will probably be the only one working on the project, it is a small project, all my controllers extend the main Controller (so I could just load one library like class there).
As a concrete example, I want to have an array of categories. So I started out with putting that array in the CategoryController. But now I noticed I kinda want to use that array in my frontview and in ProductController as well. Obviously I don't want to load all of CategoryController into ProductController.
You could also say I could put that array in some kind of configuration or settings file, because of the simpleness of this example, but that's why it's an example. I will probably expand on it with more functionality.
So to summarize: In PHP (specifically inside a MVC model) how can you give your classes (mainly Controllers) access to some kind of common class or other sharable functionality.
Your controllers are created by "something" (usually a front controller). So when the controller is created, you could inject a dependency injection container.
And in your configuration/bootstrap (before the controller is created), you should add you categories to the container.
That way you can access the categories from every controller.
Please note that this is a simple example that doesn't totally fit the spirit of dependency injection. The best solution would be to inject directly the categories (instead of injecting the container). But that can become a lot of work if you generalize that pattern (lots of dependencies to handle in your front controller).
A solution would be to use a dependency injection framework that could do that for you.
For example I work on a DI container that lets you inject stuff with annotations (PHP-DI), but there are several other libraries for DI so you have a choice.
My 2 cents:
In a small self-made mini-framework I have done some time ago, I have created a global singleton class named Application, and anything/everything which should be accessible from anywhere/everywhere was a property or method of this class.
In my case, there was a $db property for database access, a $user property to access the user data and methods, an $input property for a "powered" $_REQUEST access, and so on.
Of course, you have many other options, suitable for different scenarios. This approach simply worked fine for me on that occasion.
Now, if you want to access a controller from another controller, this really sounds strange. This "thing" that you want to access should be a model class, a library class, or anything else, but it should not be "locked" inside a controller class. Indeed, the controller should be "as thin as possible", and focus on calling the appropriated methods from other classes, based on the user input (request) and then calling some output method to generate and send the answer (response).
Finally, although I've read some criticism and complaints about it (as well as praises too), I do make use of static methods a lot, mainly for classes which are more "helpers" than anything else.
Its been couple of years I have been working on Codeigniter and I just wanted to check design patterns. I wanted to implement different design patterns on my working projects so I could understand these stuffs in a better way.
I know Codeigniter is following MVC pattern, but which design pattern is codeigniter following ?
Can we say a database.php, a database class is implementing a singleton design pattern ? I am saying since as far as I percieved, on singleton, a single instance is created which provides a global access and that is what CI database config object does.
Yes, Codeigniter's loader currently follows the singleton pattern, or at least that's the pattern that most accurately describes it. When you execute the following:
$this->load->library('foo');
$this->load->model('foo');
$this->load->database('foo');
The loader does the following things:
Check to see if the class you're loading has been loaded previously by checking a registry of loaded classes. Silently ignore the request with a debug log entry if it has been loaded.
Instantiate the class with whatever parameters you set, create a reference to that object within the framework (singleton-ish) super object named after the class, or whatever custom name you pass. Store the reference, ignore subsequent attempts to load.
On bootstrap, the magic functions in the global scope behind the loader methods are used to construct the DB, core libraries, etc.
A more traditional singleton approach would do something like this (with auto loading):
return $className::instance();
... Where the instance method would return an instance, or construct if not yet instantiated, thus obviating any need to keep track of what has or has not been loaded. If the class has been loaded, a reference would be passed, otherwise a new object would be created and returned.
I suppose technically, CI is its own pattern in this regard, but close enough to a singleton that the term does accurately apply. It really is a singleton, just not implemented in a typical way.
At last I checked there were patches floating around for CI-3 that makes the loader much more flexible, allowing one to work outside of the super object as they please by returning an object or reference in these cases, but I don't know the status of Ellis Labs taking them.
Im trying to unit test my controllers, but every tutorial I found on the internet says that I should use $this->dispatch("controller/action") to run the specific action I want to test. But doing it like that, I can't mock anything like data mappers, or other calls to other methods.
To solve this, I was trying to get an instance of the controller class, and then calling directly to the methods I wanted to test, but doing it like this, I get an error:
Zend_Exception: Setting request object manually is not allowed
Im not even sure this is the right approach, because I dont really know how I will test things doing it like this.
My test case: http://pastie.org/1812717
My ControllerTestCase: http://pastie.org/1812722
Any help would be appreciated.
Thank you.
You have two solutions:
Pseudo unit testing (more like acceptance testing) with Zend_Test_PHPUnit_ControllerTestCase
Creating new instance of the Controller, passing all the required dependencies (dispatcher, request, response, plugin managers etc.)
Both of them actually require dispatching process. The first, dispatching the application, second, dispatching the controllers.
See the manual and sample tests from the full Zend Framework package.
Also, look at the controller source code, to see, how the dependencies are managed.
See also other SO posts about Dependency Injection to the Zend Framework controllers.
I would guess that Zend_Test_PHPUnit_ControllerTestCase is preventing you from being able to mock Requset and Response objects. I would bypass it and just extend PHPUnit_Framework_TestCase. As I mentioned in another question, I am currently mocking Controllers without any problems.
Here is an example test that runs fine:
http://pastie.org/1816705
AbstractRestController is simply a controller class that extends Zend_Controller_Action
How is your data mapper (or other objects) instantiated? Are you instantiating it directly in the controller or grabbing it from the bootstrap/registry? If using registry or bootstrap, then place the mock in the registry/bootstrap.
If you are directly instantiating in the controller, you will need to modify your controller. Maybe have a controller method to set the data mapper, and then have another method to grab the data mapper, and if one is not set, then instantiate it. That allows your tests to inject a mock.
I typically don't mock many classes when testing controllers - I want to test the entire app and its ability to render the page... It looks like you are testing no records in the database, so why not use Zend_Test_PHPUnit_Db to set up an empty table for that test, rather than mock the data mapper to return no data?
I’m fairly new to CodeIgniter and have a question. I’m a bit confused about Classes, Libraries and Objects.
Does CodeIgniter replace the normal PHP way of usings objects i.e. $var = new car(); with libraries i.e. $this->load->library('some_library'); $this->some_library->some_function(); ?
If both are valid, is there a difference? If so, what are the differences and when do I use one over the other? Which is more common/proper?
I am asking because I created a class, but I'm not certain what is the correct manner in which to instantiate it.
Thanks in advance
I am not familiar with CodeIgnitier. But familiar with other PHP frameworks. Most of frameworks use this way for performance improvements, registering things, executing certain events, and making things simpler for developer...
For example if you want to create class "car" with is somewhere in library directory you would have to include the file first before you can create object of that class (miltiple lines of code, more room for error). The framework will create the class and includes related files in 1 line of code (easier and safer).
Framework way also works as a factory. Instead of recreating an object, it will create object only once and every time you call the method again it will return the reference to existing object.
More things are happening behind the scenes when you use framework. Things are getting registered, etc...
CI doesn't replace class behavior per se, it simply adds functionality that allows access to custom libraries/models/views as singleton objects via the core object for simplicity.
Nothing is stopping you from creating (as I have in one of my projects) additional files with classes for non-singleton entities and require them in a model for further use. On hindsight, I should probably have used helpers for this.
What the loader ($this->load) class does, among other things, is it creates a single object of the specified class (model, library or view - not helpers though, see below) and attaches it as a property of the core class that is normally accessible via $this.
Helpers are a bit different. They are not attached, but instead simply 'read' into the global namespace from the point where they are loaded.
To answer your question, it would be more proper to use the loader class in instances where you don't need more than one instance of a class created. If you need 'entity' classes, your best CI-compliant bet would be to create them as helpers.
Given only this context, this looks like Inversion of Control (maybe I'm wrong, I haven't looked too closely at CodeIgniter).
You don't want to rely on the type car as in new car(). What if later you want to make $var a racecar? $var can still do the same things, but it is forced to be a car because you constructed it directly. Or what if you are testing this class, but car is some complex object which calls some external service. You want to test your logic, but don't care if the car service isn't working. So you should be able to change $var to actually load a mockcar. You can't do that if you do $var = new car().
What is Inversion of Control?
I'm experiencing what I believe is a circular dependency issue with my PHP application. Please let me know if this is incorrect. Here is the situation:
Two classes, LogManager and DBSession.
DBSession is used to interact with the database, and LogManager is used to log to files. Both are widely used in my application. When you create an instance of DBSession, you must give it an instance of LogManager via a constructor parameter. This because DBSession will sometimes log information to a file, and will use the LogManager instance to do this.
Now, I wanted to extend LogManager so that it could also log to a database table, rather than a text file. Naturally, my preference is to re-use existing classes, but I soon realized this brought about an interesting situation.
DBSession already requires an instance of LogManager for construction. If I want to re-use the DBSession class in LogManager, it will now require an instance of DBSession. How can I satisfy both demands? Clearly, something must be wrong with my approach.
How would you suggest I fix this?
Thanks in advance, guys.
Don't extend LogManager, let it be an aggregate type. And delay the choice of where you want to log, i.e.:
$logManager = new LogManager();
$dbSession = new DbSession($logManager);
$logManager->add(new FileLog($filename) );
$logManager->add(new DBLog($dbSession) );
Where of course FileLog and DBLog share a common interface.
This is an application of the Observer pattern, where add() is the "subscribe" operation, and FileLog/DBLog are the observers of logging events.
(In this way you could also save logs in many places.)
Owen edit: adjusted to php syntax.
One of these objects doesn't actually need the other: you guessed it, it's the DBSession. Modify that object so that the logger can be attached to it after construction.
Why demand a LogManager object for the creation of a DbSession object, if it only sometimes writes to files? lazy load it instead only when you need it. Also, in my opinion both should be independent from each other. Each could instance the other when needed.
Maybe you can apply some pattern, like the Singleton Pattern to ensure that you only have one instance of your LogManager class for example.