I have a main controller and I want to call child controllers from this controller with HMVC. I setted a rule that routes parameter to a specific action that calls children controllers with "Request::factory" for the main controller but it didn't work because of infinity loop. is there any way to do it?
I must use HMVC because main controller sends some information to children controller so I need a controlling layer.
It will be kind of a plugin for crud applications for a CMS.
The main controller: http://pastebin.com/nt2fhMEy
An example of child controller: http://pastebin.com/WqaHZaxf
Route: http://pastebin.com/6JGFf2i2 (I didn't configure caction and cid yet.)
Extra Note: It will be kind of a crud module for my CMS. The main controller will load main template and some configs. Also the main controller includes some ORM functions and children controller must be able to use parent::functionname. The children controllers are in cruds/ directory and the cms creates them automatically.
You have a few mistakes in your idea of the controllers and HMVC.
The best way to do so is to use object oriented controllers. By this I mean the "child controllers" need to extend the main controller.
Let the main controllers extend Controller_Template and the child controllers extend the main controller.
When you send requests to child controllers through routes you will not only have access to the parent properties, but your request will do the following:
Before method of the main controller
Before method of the child controller.
Action of the child controller.
After method of the child controller.
After method of the parent controller.
From what I get from your question you will not need HMVC at all. Actually it's a very bad pattern for passing data. Keep in mind that when you perform an internal request through HMVC this is actually a completely new request. It will go through the routes and this list again. You will not have access to all of the previous request properties.
Another tip: don't put ORM functions in the main controller. Use the actual ORM models instead.
Related
I'm currently trying to build an Angular2 prototype (based on alpha44) of our Angular1 app (pretty complex one) and I'm trying to find the best model/data architecture when using routes and child routes.
In my example, from a child component created from a route, I want to access a property of the parent component (hosting the router-outlet).
But when you create a component from a router-outlet, you cannot use #Input and #Output anymore.
So what is the best practice to inject some data/properties, except basic routeParams and static routeData?
How do you communicate with the parent component without too much coupling?
You can use RouteData in order to pass data into routes. See here and here. I'm still missing the part of initialising this data obj from the component (see my question regarding)
A shared service can be used with components added by the router. For details see https://angular.io/docs/ts/latest/cookbook/component-communication.html
data support also was added to the new router in RC.4. For details see How do I pass data in Angular 2 components while using Routing?
Angular 2 - equivalent to router resolve data for new router might also be related.
You can pass (inject) data from child component inside Router Outlet to Parent component with Subject,Observable. You can found my solution in this video.
See the code on GitHub: https://github.com/tabvn/angular-blog
Before I added [Authorize] filters for each controller, I created test cases and made them pass. Now I have added said filter on each controller's method but they still pass, but I think they shouldn't since there is no logged user. Am I not seeing something?
PS: I haven't mocked Identity 2.0
Edit:
Basically I'm mocking a repository, through the unit of work pattern. In my unit test, I get a reference to the List the mock repository uses, in order to test.
[TestMethod]
public async Task CanCreateCustomerAndRedirectToDetails() {
// Arrange
Customer customer = NewCustomer(); // Gets a new customer that is NOT on the list
CustomerCreateViewModel viewModel = Mapper.Map<CustomerCreateViewModel>(customer); // Maps to viewmodel
// Act
RedirectToRouteResult result = (RedirectToRouteResult) await Controller.Create(viewModel); // Sends to controller
// Assert
// Up to this point, Customers is the mock repository's list. so it should contain the new created customer since the controller should call the insert method
// Normally, the assertion should pass. But after I implemented [Authorize] filter, I would expect the controller not to do anything (besides redirecting to login) and this test would fail
Assert.IsNotNull(Customers.FirstOrDefault(e => e.ID == customer.ID));
Assert.AreEqual("Details", result.RouteValues["action"].ToString());
}
There's nothing in your unit test which responds to or in any way examines the Authorize attribute. Or any attribute.
Attributes don't actually change the behavior of the method. They decorate the method in a way that other code (such as in a framework, like ASP.NET MVC) might recognize. The Authorize attribute is used by the ASP.NET MVC framework. But the attribute alone doesn't change the method.
MSTest doesn't use the Authorize attribute. So if you want to test its presence on the method, you'd need to examine it in some way. Though that shouldn't really be necessary. The functionality of the framework is already very thoroughly tested by its vendor.
All your test needs to be testing is the functionality of the method, which it is. You don't need to test the functionality of the ASP.NET Framework.
You can test attributes very effectively by unit testing the classes which define those attributes. So if you, for example, created a custom attribute (let's call it CustomAuthorize) then you would have a class defining that attribute (CustomAuthorizeAttribute) and you could unit test that class, separately from unit testing your controllers.
Is there is a way to invoke onExit() Life cycle hook manually?
If you´re talking about the onExit function of your controller you can! However, you should consider the View Lifecycle. According to this Lifecycle the framework will automatically call the onExit hook for you:
onExit(): Called when the view is destroyed; used to free resources and finalize activities
Source: SAPUI5 Documentation
Since it is a function which belongs to your controller you are able to call it manually by this.onExit() (in your controller).
However, this shouldn´t be necessary. To act according to the lifecycle you can call .destroy() of your view which destroys the view, the controller and all associated children.
destroy(): Cleans up the resources associated with this element and all its children.
Source: SAPUI5 Documentation
I would like to ask, What would be the most suitable scope for my upload photo service in Grails ? I created this PhotoService in my Grails 2.3.4 web app, all it does is to get the request.getFile("myfile") and perform the necessary steps to save it on the hard drive whenever a user wants to upload an image. To illustrate what it looks like, I give a skeleton of these classes.
PhotoPageController {
def photoService
def upload(){
...
photoService.upload(request.getFile("myfile"))
...
}
}
PhotoService{
static scope="request"
def upload(def myFile){
...
// I do a bunch of task to save the photo
...
}
}
The code above isn't the exact code, I just wanted to show the flow. But my question is:
Question:
I couldn't find the exact definition of these different grails scopes, they have a one liner explanation but I couldn't figure out if request scope means for every request to the controller one bean is injected, or each time a request comes to upload action of the controller ?
Thoughts:
Basically since many users might upload at the same time, It's not a good idea to use singleton scope, so my options would be prototype or request I guess. So which one of them works well and also which one only gets created when the PhotoService is accessed only ?
I'm trying to minimize the number of services being injected into the application context and stays as long as the web app is alive, basically I want the service instance to die or get garbage collect at some point during the web app life time rather than hanging around in the memory while there is no use for it. I was thinking about making it session scope so when the user's session is terminated the service is cleaned up too, but in some cases a user might not want to upload any photo and the service gets created for no reason.
P.S: If I move the "def photoService" within the upload(), does that make it only get injected when the request to upload is invoked ? I assume that might throw exception because there would be a delay until Spring injects the service and then the ref to def photoService would be n
I figured out that Singleton scope would be fine since I'm not maintaining the state for each request/user. Only if the service is supposed to maintain state, then we can go ahead and use prototype or other suitable scopes. Using prototype is safer if you think the singleton might cause unexpected behavior but that is left to testing.
I'm new to angular and developing my first 'real' application. I'm trying to build a calendar/scheduling app ( source code can all be seen on github ) and I want to be able to change the content if there is a user logged in (i.e. display details relevant to them) but here's the catch:
I don't want the app to be dependent on having a logged in user ( needs to be something that can be configured to work publicly, privately or both)
I don't want to implement the user/login within this app if it can be avoided ( I want to eventually include my app in another app where this might be implemented but isn't necessarily implemented using any particular security frameworks or limited to any)
I had an idea of creating some global variable user that could be referenced through out my application, or if I had to implement a system to do it all in this app that I could do so in in some abstract way so that different options could be injected in.
some of my ideas or understanding of what I should be doing may be completely wrong and ignorant of fundamentals but I genuinely do not know what approach I should take to do this.
In case it is relevant I currently don't have any back-end but eventually hope use MongoDB for storage and nodejs for services but I also want to try keep it open-ended to allow others to use different storage/backends such as sql and php
is there away to have a global uservariable/service that I could inject/populate from another (parent?) app?
If so what would be the best approach to do so?
If Not, why and what approach should I take and why?
Update
I Believe from comments online and some suggestion made to me that a service would be the best option BUT How would I go about injecting from a parent application into this applications service?
If your (single) page is rendered dynamically by the server and the server knows if you are logged-in or not, then you could do the following:
Dynamically render a script tag that produces:
<script>
window.user = { id: 1234, name: 'User A', isLoggedIn: true };
</script>
For non logged-in users:
<script>
window.user = { isLoggedIn: false };
</script>
For convinience, copy user to a value inside angular's IOC:
angular.module('myApp').value('user', window.user);
Then, you can use it in DI:
angular.module('myApp').factory('myService', function(user) {
return {
doSomething: function() {
if (user.isLoggedIn) {
...
} else {
...
}
}
};
});
Something tricky (which you should thing twice before doing [SEE COMMENTS]) is extending the $scope:
angular.module('myApp').config(function($provide) {
$provide.decorator('$controller', function($delegate, user) {
return function(constructor, locals) {
locals.$scope._user = user;
return $delegate(constructor, locals);
};
});
});
This piece of code decorates the $controller service (responsible for contructing controllers) and basically says that $scope objects prior to being passed to controllers, will be enhanced with the _user property.
Having it automatically $scoped means that you can directly use it any view, anywhere:
<div ng-if="_user.isLoggedIn">Content only for logged-in users</div>
This is something risky since you may end up running into naming conflicts with the original $scope API or properties that you add in your controllers.
It goes without saying that these stuff run solely in the client and they can be easily tampered. Your server-side code should always check the user and return the correct data subset or accept the right actions.
Yes you can do it in $rootScope. However, I believe it's better practice to put it inside a service. Services are singletons meaning they maintain the same state throughout the application and as such are prefect for storing things like a user object. Using a "user" service instead of $rootScope is just better organization in my opinion. Although technically you can achieve the same results, generally speaking you don't want to over-populate your $rootScope with functionality.
You can have a global user object inside the $rootScope and have it injected in all your controllers by simply putting it into the arguments of the controller, just as you do with $scope. Then you can implement functionalities in a simple check: if($rootScope.user). This allows you to model the user object in any way you want and where you want, acting as a global variable, inside of Angular's domain and good practices with DI.
Just to add on my comment and your edit. Here is what the code would look like if you wanted to be able to re-use your user service and insert it into other apps.
angular.module('user', []).service('userService', [function(){
//declare your user properties and methods
}])
angular.module('myApp', ['user'])
.controller('myCtrl', ['userService', '$scope', function(userService, scope){
// you can access userService from here
}])
Not sure if that's what you wanted but likewise you could have your "user" module have a dependency to another "parent" module and access that module's data the same way.