Application Init Handler Equivalent in Angular? - model-view-controller

I would like to "simulate" global variables in Angular. I would also like to be able to initialize those "global variables" in an App_Init()-type of handler. Such an initialization will require $http calls to populate those variables. I want all of the "global variables" to be completely loaded before Angular "calls up" controllers and views, because controllers would depend on the initialized data.
What are some best practices for that in Angular? Nested controllers? Services?
Example: An app that manages items in a restaurant's menu. Each item will be associated with a category (beverage, appetizer, dessert, etc.). I need to load all of those categories first before Angular "even touches" the controllers and views for the food items.

Are you using ng-view and the $routeProvider service for your app? Assuming you are or will consider, here is what you can do in order of steps:
Build a service that provides acces to the categories to its called. My idea is that this service would load the categories from the server when it's first called and then cache the data loaded, so the next time it's called a cache copy is served, instead, to save a request to the server. Let's call this service categories for now.
Use the resolve property of route object to ensure the dependency on the categories service is resolved before loading the view the user is requesting (and the corresponding controller). As a result, you can inject the categories service into the controller and be sure the service is always available because it has already been resolved.
If you have never worked with the resolve property in configuring routing before, Here is an example and the part of the official docs that talks about it. I recommend you go through them.
Also, in order to understand how resolve works, you need to be familiar with the concept of promise and deferred. If you are not, here is a good starting point on the topic. $q is AngularJS's implementation of promise/deferred.
I can't comment on if the above approach is the best practice, but I know it's a good practice to use service to provide access to some data/functions like if there were global variables.

You can create a service to load the configuration from server and put it in rootScope, in your controller you can call this service on your function and this function you call from ng-init in your view.
View
<mytag ng-init="myFunc()">
Controller
module.controller('MyCtrl', function($scope, myService){
$scope.myFunc = function(){
myService();
}
}
your service (initialize app)
module.service('myService', function($http, $rootScope){
//do something
$rootScope.config = configLoaded;
}
another tip
if you are in trouble with asynchronous calls you can try to use
var deferred = $q.defer();
//when your call come back
deferred.resolve(yourData);
//and in the last line of function
deferred.promise;

Related

Call controller within another controller - CodeIgniter

I need to call a controller say 'faq_view' inside admin controller as the URL structure admin/faq_view like this how I can do this?
e.g:
site.com/maincontroller/function
site.com/maincontroller/othercontroller/function
Then, just redirect the page. Else if you want to just call the function, call it via AJAX.
It depends what you exactly want to do. If you want to just invoke the function, its not the right way. Controller as it defines itself controls the flow of the pages that comes on sequence. Controller is responsible to send commands to its associated view to change the view's presentation of the model.
So, if you are saying you want to call controller within another controller, that should mean you are about to redirect to another page.
Updated answer:
Just assume you have new_function on maincontroller that calls the function from othercontroller. The function does not need to be defined on othercontroller.
Add the following line on routes.php.
$routes['maincontroller/new_function'] = 'othercontroller/new_function';
Now, you can call the function of othercontroller as maincontroller/new_function.
You can always call a controller inside another controller, but this only works for calling one controller as far as I have tried. Let's say you are trying to load a controller inside a controller. You can try this:
$this->load->library('../controllers/myothercontroller');
Then do this:
$this->myothercontroller->function_name();
That's it! You can now access any function inside myothercontroller (controller) in your current controller. I hope this helps too.
Your controllers are part of the presentation layer and should not contain application logic. That means you should never need to call a controller from another controller, instead refactor your application and move the domain logic to the model layer.
Now if you have a method that you need in multiple controllers, say for example you need a template method that automatically adds your header and footer views.
If that is the case, create a base class that your controllers extend.
If you are talking about just a routing issue, then just use the routes file for that. I don't like the CI automatic routing and it should be avoided as it will result in duplicate URLs for the same resource.

What is the correct place/bundle to place this action

Say I have a CoreBundle, which has an entity called Event. In the CoreBundle, events can e.g. be shown (showAction). I also have a BackendBundle. The event's deleteAction can only be triggered from the backend. However, the deleteAction belongs to an entity that is defined in the CoreBundle. Both the CoreBundle and the BackendBundle have an EventController.
The question is: Should the deleteAction be placed in the BackendBundle's EventController or in the CoreBundle's EventController?
P.s. I know both will work, but this is more somewhat of a phylosophical question.
I would suggest you have a BackendBundle with an EventController and a deleteAction. This deleteAction may call a specific handler (or manager or whatever) inside the CoreBundle, but I would keep the controller code inside the BackendBundle.
First, it makes it easy to follow the code without switching bundles. I can see that the request comes in, that either the entity is deleted or that some manager is called and that a redirect is send or a template is rendered.
Second, and way more important, is that if you introduce another bundle which has a deleteAction for the backend, you can either have different ways of handling them (one inside it's own bundle and one inside the CoreBundle) or you have to name them different and create a big mess.
In generell, I stick to the rule to have the controller inside the same bundle where the route and the view lives and only share the model. In case of a CoreBundle, I handle deletion with a manager between the controller and the model. In your case the deleteAction would get a EventManager service and call a delete with either the object or an id (depending on my needs). This way the code executed to delete an event is in one place and can be changed easily.

ZF2, create dynamic menu at module initiation

I have a menu which I need to create dynamically (some blog pages are added from a database). ZF2 Dynamic Menu with Zend\Navigation\Navigation addresses how to do this for an individual controller/action.
But how should this be done for all requests, at the moment of initialising the module?
I need at least the routeMatch object (to get the language parameter) and I have seen the below to get that:
public function onBootstrap(EventInterface $e)
{
$app = $e->getApplication();
$em = $app->getEventManager();
$em->attach(MvcEvent::EVENT_ROUTE, function($e) {
$routeMatch = $e->getRouteMatch();
});
}
But in the docs it says:
"the onBootstrap() method is called for every module implementing this feature, on every page request, and should only be used for performing lightweight tasks such as registering event listeners."
What would be the best place and way to initialise dynamic navigation (or other more complicated logic) in Zend Framework 2?
The correct place is indeed bootstrap to do this sort of things. Bear in mind the code at bootstrap is run at every request, so make it as lightweight as possible. If you want to inject navigation, try to cache the navigation structure from your database and inject the version from cache.
This behaviour is something I did in ensemble. It fetches data from the database to build routes dynamically and based on the routes, the navigation structure is build. The routes and navigation are injected in respectively the router and navigation container, so at dispatch of the application is seems there is nothing different from a "normal" request with routes configured in the module.config.php.
For some examples you should check out the kernel, currently only availble with a Doctrine adapter (Zend\Db coming soon). It registers listeners to hook up early, it parses the database results into a route and navigation structure and those can be cached to increase performance.
If you need more specific information, please update your question to ask more about what you miss in the bigger picture.

Codeigniter Inter Controller Communication

I am new to MVC, CodeIginter. Instead of getting things easy, it needs lot of code to be written for a simple application. These are might be happening becouse I am new. So I have few confusions about this thing. Any kind of help is appreciated.
1) Methods are written in one controller can not be accessed in another controller classes. I have to write a new function for the same functionality.
2) To create website administration panel (back-end) in none mvc panel, we usually create it in a new folder. Is this thing possible in CodeIgniter? If not what about the admin (back-end)??
Let's try to clear some of your doubts about this.
1) Calling a controller's method from another controller is not possible, and it's whtouth meaning by the way.
A controller is supposed to get an action from the URL (which is routed by CI to the right controller for the task) and, based on that, decide which Model and which model's method needs be called to elaborate the data requested.
The model, then, hands back the result of this elaboration to the controller, which , in turns, decides to which view pass this results.
The view, eventually, is structured to get those datas and display them.
SO, as you can see, calling a controllers' method from another controller is nonsense, it would be like going to a page and finding another one instead; if you want to pass to another controller the request...well, there's the redirect for that.
If you find out you have the same functionalities in several moment, think twice:
What is a funcionality? Do you mean somehtin like "display posts" in controller "archive" and "display posts" in controller "news" ? they're hardly the same functionality; they can maybe share views, or models, but that's it.
For functions that doesn't relate to URLs, but involve some further elaboration (which might be wrong to do in Models) and are nonetheless called in a controller, you have library instead. Think at the "form_validation" library, which is called in a controller's method, but has its own peculiar (and encapsulated) functionalies. Ora a "session" library, or an "authentication" library
2) To create an admin panel the easiest thing is: create an "admin" controller (which is accesible then to www.mysite.com/index.php/admin), and put all the administration actions there, in its methods: create_page(), edit_page(), manage_users(), whatever.
In order to avoid people accessing it freely you need to build an authentication system, which, in its simplest and barabone strucutre, might be a check of wheter a session is set or not (maybe a check done at __construct() time).
But you can find nice Auth libraries out there already made, such as Ion Auth or Tank Auth (the 2 most popular to my knowledge)
Hope things are a bit clearer now. See also Interstellar_Coder's comment at this answer if you're interested in the modular HMVC approach.
1) Methods are written in one controller can not be accessed in another controller classes. I have to write a new function for the same functionality.
What's the functionality about? Perhaps you should write a library/helper instead, controller's logic should be limited to request flow or something else but not too complicated. For that, put the functionality in the model, or if more general, in library/helper.
2) To create website administration panel (back-end) in none mvc panel, we usually create it in a new folder. Is this thing possible in CodeIgniter? If not what about the admin (back-end)??
I don't get it, could you elaborate more?

CodeIgniter: Lifecycle of the Controllers

The text is quite long, the question is actually simple and written in bold. The other text is only for trying to explain the problem.
I have recently started to use CodeIgniter for developing my website. Currently, I'm writing a side menu where you can filter the items showed in the view (basic e-commerce functionality).
The idea I had was to have an array in my Shop-controller where I store my filtering values which are passed to and from my filterview, so the filter menu kan handle several types of filters.
The problem is that it seems like the constructor of the controller is run each time the controller is called. I thought that the controller was constructed only once when the user enters the website. I'm pretty new at website devlopment and am mainly a C++-guy, so this seems a bit strange for me.
My question is pretty simple actually: Is it true that the controller instance is created at each call to a controller function? Otherwise, what am I doing wrong to cause the controller instance to be reinstantiated at each controller call...
I hope that my question is not too fuzzy. It is important for me to understand the lifecycle behaviour of CodeIgniter to be able to find a simple solution for this. I would like to avoid using $_SESSION, because I would like to use a OOP like solution.
Is it true that the controller
instance is created at each call to a
controller function? Otherwise, what
am I doing wrong to cause the
controller instance to be
reinstantiated at each controller
call..
Yes, the controller instance is re-instantiated every time you make a call to that controller. In CodeIgniter, there is no such thing as a persistent instance of your controller for each user interacting with your application (unlike single-user apps built in C++). What you do have is session management, where you use Session variables to store data persistent to that particular session between the user's browser and your web server (more). Another way to do this is by using cookies. I personally prefer session over cookies.
There is no harm in using $_SESSION for the purpose of your filter, and it is not against OOP principles. What matters is how you use the data stored in your Session variable once your controller instance has loaded ( that's where the OOP concepts come into play).
Shivaas, the same answer can by safely used with models? What about autoloading models? I mean, autoloading it's just a way to avoid typing $this->load->model('the_model') when needed? There's no way to use singleton pattern without recurring to use session/database?
private $instance;
function init_model() {
if ($this->instance === NULL) {
$this->instance = array();
}
return $this->instance;
}
Once init_model exits, the class instance is destroyed so $instance will be always initialized to a new array()?

Resources