Avoiding duplicate data & calculations in view-models - apache-flex

I'm working on a Flex application that uses MVVM. I understand that it's recommended to have a 1-to-1 mapping between views and view-models. How then do I avoid performing the same calculations and storing the same data multiple times if it is needed in multiple views?
For example, imagine I have a program that can load project files consisting of a list of items. The main tab of my application has an export button that should only be enabled if the project is valid so I create an isExportEnabled property on the view-model for the main tab. The calculation for this involves validating the project by iterating though every item in the project and verifying some attribute on each. I have another tab which has a "Print Project Summary" button so the view-model for this tab has isPrintEnabled. The value for this flag is based on the same criteria, whether or not the project is valid.
I could put the logic for determining these values in their respective view-models, but then I end up calculating the same value twice when a project is loaded.
I could move isValid to the domain model but then the model becomes denormalized. What if a saved project is edited without updating the "isValid" flag?
I could make a global "Project View-Model" for the entire project which calculates whether the project is valid and then have isExportEnabled and isPrintEnabled delegate to that. However, then I end up with a hierarchy of view-models which this article recommends avoiding: Applying the Presentation Model in Flex
It feels like there is no correct way to do this.

So you are saying you have two user gestures, "Export" and "Print Project Summary" which are based on the same validation function ? If I read your post right then you can calculate it once and have two getters
private var _isValid:Boolean;
public function validate():Boolean
{
_isValid = //result of calculation
dispatchEvent( new Event("isValidChange") )
}
[Bindable(Event="isValidChange")]
public function get canExport():Boolean
{
return _isValid;
}
[Bindable(Event="isValidChange")]
public function get canPrint():Boolean
{
return _isValid;
}
Now some may say that since they are returning the same value that we should get rid of the getters and return a simple [Bindable] public value. But since this seems like the first implementation of this feature, having two separate functions allows you some robustness in the face of changing UI and validation requirements.
Personally, if the validation logic got too heavy, I would keep that value on my model "public var isValidProject" since the model should know if it is valid or not. Then the presentation layer would use that value to determine how to represent to the user that this is an invalid project (popups,alerts,error strings ).
In other cases, I would make a setter on the presenter of those buttons "set selectedProject" and run my validation and/or change my buttons enablement state there.
I would really be interested to hear others thoughts on this.

Related

Sf2 : using a service inside an entity

i know this has been asked over and over again, i read the topics, but it's always focused on specific cases and i generally try to understand why its not best practise to use a service inside an entity.
Given a very simple service :
Class Age
{
private $date1;
private $date2;
private $format;
const ym = "%y years and %m month"
const ...
// some DateTime()->diff() methods, checking, formating the entry formats, returning different period formats for eg.
}
and a simple entity :
Class People
{
private $firstname;
private $lastname;
private $birthday;
}
From a controller, i want to do :
$som1 = new People('Paul', 'Smith', '1970-01-01');
$som1->getAge();
Off course i can rewrite the getAge() function inside my entity, its not long, but im very lazy and as i've already written all the possible datetime->diff() i need in the above service, i dont understand why i shouldnt use'em...
NB : my question isnt about how to inject the container in my entity, i can understand why this doesnt make sense, but more what wld be the best practise to avoid to rewrite the same function in different entities.
Inheritance seems to be a bad "good idea" as i could use the getAge() inside a class BlogArticle and i doubt that this BlogArticle Class should be inheriting from the same class as a People class...
Hope i was clear, but not sure...
One major confusion for many coders is to think that doctrine entities "are" the model. That is a mistake.
See edit of this post at the end, incorporating ideas related to CQRS+ES -
Injecting services into your doctrine entities is a symptom of "trying to do more things than storing data" into your entities. When you see that "anti-pattern" most probably you are violating the "Single Responsibility" principle in SOLID programming.
http://en.wikipedia.org/wiki/Anti-pattern
http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29
http://en.wikipedia.org/wiki/Single_responsibility_principle )
Symfony is not an MVC framework, it is a VC framework only. Lacks the M part. Doctrine entities (I'll call them entities from now on, see clarification at the end) are a "data persistence layer", not a "model layer". Symfony has lots of things for views, web controllers, command controllers... but has no help for domain modelling ( http://en.wikipedia.org/wiki/Domain_model ) - even the persistence layer is Doctrine, not Symfony.
Overcoming the problem in SF2
When you "need" services in a data-layer, trigger an antipattern alert. Storage should be only a "put here - get from there" system. Nothing else.
To overcome this problem, you should inject the services into a "logic layer" (Model) and separate it from "pure storage" (data-persistence layer). Following the single responsibility principle, put the logics in one side, put the getters and setters to MySQL in another.
The solution is to create the missing Model layer, not present in Symfony2, and make it to give "the logic" of the domain objects, completely separated and decoupled from the layer of data-persistence which knows "how to store" the model into a MySQL database with doctrine, or to a redis, or simply to a text file.
All those storage systems should be interchangeable and your Model should still expose the very same public methods with absolutely no change to the consumer.
Here's how you do it:
Step 1: Separate the model from the data-persistence
To do so, in your bundle, you can create another directory named Model at the bundle-root level (besides tests, DependencyInjection and so), as in this example of a game.
The name Model is not mandatory, Symfony does not say anything about it. You can choose whatever you want.
If your project is simple (say one bundle), you can create that directory inside the same bundle.
If your project is many bundles wide, you could consider
either putting the model splitted in the different bundles, or
or -as in the example image- use a ModelBundle that contains all the "objects" the project needs (no interfaces, no controllers, no commands, just the logic of the game, and its tests). In the example, you see a ModelBundle, providing logical concepts like Board, Piece or Tile among many others, structures in directories for clarity.
Particularly for your question
In your example, you could have:
Entity/People.php
Model/People.php
Anything related to "store" should go inside Entity/People.php - Ex: suppose you want to store the birthdate both in a date-time field, as well as in three redundant fields: year, month, day, because of any tricky things related to search or indexing, that are not domain-related (ie not related withe lo 'logics' of a person).
Anything related to the "logics" should go inside Model/People.php - Ex: how to calculate if a person is over the majority of age just now, given a certain birthdate and the country he lives (which will determine the minumum age). As you can see, this has nothing to do on the persistence.
Step 2: Use factories
Then, you must remember that the consumers of the model, should never ever create model objects using "new". They should use a factory instead, that will setup the model objects properly (will bind to the proper data-storage layer). The only exception is in unit-testing (we'll see it later). But apart from unitary tests, grab this with fire in your brain, and tattoo it with a laser in your retina: Never do a 'new' in a controller or a command. Use the factories instead ;)
To do so, you create a service that acts as the "getter" of your model. You create the getter as a factory accessible thru a service. See the image:
You can see a BoardManager.php there. It is the factory. It acts as the main getter for anything related to boards. In this case, the BoardManager has methods like the following:
public function createBoardFromScratch( $width, $height )
public function loadBoardFromJson( $document )
public function loadBoardFromTemplate( $boardTemplate )
public function cloneBoard( $referenceBoard )
Then, as you see in the image, in the services.yml you define that manager, and you inject the persistence layer into it. In this case, you inject the ObjectStorageManager into the BoardManager. The ObjectStorageManager is, for this example, able to store and load objects from a database or from a file; while the BoardManager is storage agnostic.
You can see also the ObjectStorageManager in the image, which in turn is injected the #doctrine to be able to access the mysql.
Your managers are the only place where a new is allowed. Never in a controller or command.
Particularly for your question
In your example, you would have a PeopleManager in the model, able to get the people objects as you need.
Also in the Model, you should use the proper singular-plural names, as this is decoupled from your data-persistence layer. Seems you are currently using People to represent a single Person - this can be because you are currently (wrongly) matching the model to the database table name.
So, involved model classes will be:
PeopleManager -> the factory
People -> A collection of persons.
Person -> A single person.
For example (pseudocode! using C++ notation to indicate the return type):
PeopleManager
{
// Examples of getting single objects:
Person getPersonById( $personId ); -> Load it from somewhere (mysql, redis, mongo, file...)
Person ClonePerson( $referencePerson ); -> Maybe you need or not, depending on the nature the your problem that your program solves.
Person CreatePersonFromScratch( $name, $lastName, $birthDate ); -> returns a properly initialized person.
// Examples of getting collections of objects:
People getPeopleByTown( $townId ); -> returns a collection of people that lives in the given town.
}
People implements ArrayObject
{
// You could overload assignment, so you can throw an exception if any non-person object is added, so you can always rely on that People contains only Person objects.
}
Person
{
private $firstname;
private $lastname;
private $birthday;
}
So, continuing with your example, when you do...
// **Never ever** do a new from a controller!!!
$som1 = new People('Paul', 'Smith', '1970-01-01');
$som1->getAge();
...you now can mutate to:
// Use factory services instead:
$peopleManager = $this->get( 'myproject.people.manager' );
$som1 = $peopleManager->createPersonFromScratch( 'Paul', 'Smith', '1970-01-01' );
$som1->getAge();
The PeopleManager will do the newfor you.
At this point, your variable $som1 of type Person, as it was created by the factory, can be pre-populated with the necessary mechanics to store and save to the persistence layer.
The myproject.people.manager will be defined in your services.yml and will have access to the doctrine either directly, either via a 'myproject.persistence.manager` layer or whatever.
Note: This injection of the persistence layer via the manager, has several side effects, that would side track from "how to make the model have access to services". See steps 4 and 5 for that.
Step 3: Inject the services you need via the factory.
Now you can inject any services you need into the people.manager
You, if your model object needs to access that service, you have now 2 choices:
When the factory creates a model object, (ie when PeopleManager creates a Person) to inject it via either the constructor, either a setter.
Proxy the function in the PeopleManager and inject the PeopleManager thru the constructor or a setter.
In this example, we provide the PeopleManager with the service to be consumed by the model. When the people manager is requested a new model object, it injects the service needed to it in the new sentence, so the model object can access the external service directly.
// Example of injecting the low-level service.
class PeopleManager
{
private $externalService = null;
class PeopleManager( ServiceType $externalService )
{
$this->externalService = $externalService;
}
public function CreatePersonFromScratch()
{
$externalService = $this->externalService;
$p = new Person( $externalService );
}
}
class Person
{
private $externalService = null;
class Person( ServiceType $externalService )
{
$this->externalService = $externalService;
}
public function ConsumeTheService()
{
$this->externalService->nativeCall(); // Use the external API.
}
}
// Using it.
$peopleManager = $this->get( 'myproject.people.manager' );
$person = $peopleManager->createPersonFromScratch();
$person->consumeTheService()
In this example, we provide the PeopleManager with the service to be consumed by the model. Nevertheless, when the people manager is requested a new model object, it injects itself to the object created, so the model object can access the external service via the manager, which then hides the API, so if ever the external service changes the API, the manager can do the proper conversions for all the consumers in the model.
// Second example. Using the manager as a proxy.
class PeopleManager
{
private $externalService = null;
class PeopleManager( ServiceType $externalService )
{
$this->externalService = $externalService;
}
public function createPersonFromScratch()
{
$externalService = $this->externalService;
$p = new Person( $externalService);
}
public function wrapperCall()
{
return $this->externalService->nativeCall();
}
}
class Person
{
private $peopleManager = null;
class Person( PeopleManager $peopleManager )
{
$this->peopleManager = $peopleManager ;
}
public function ConsumeTheService()
{
$this->peopleManager->wrapperCall(); // Use the manager to call the external API.
}
}
// Using it.
$peopleManager = $this->get( 'myproject.people.manager' );
$person = $peopleManager->createPersonFromScratch();
$person->ConsumeTheService()
Step 4: Throw events for everything
At this point, you can use any service in any model. Seems all is done.
Nevertheless, when you implement it, you will find problems at decoupling the model with the entity, if you want a truly SOLID pattern. This also applies to decoupling this model from other parts of the model.
The problem clearly arises at places like "when to do a flush()" or "when to decide if something must be saved or left to be saved later" (specially in long-living PHP processes), as well as the problematic changes in case the doctrine changes its API and things like this.
But is also true when you want to test a Person without testing its House, but the House must "monitor" if the Person changes its name to change the name in the mailbox. This is specially try for long-living processes.
The solution to this is to use the observer pattern ( http://en.wikipedia.org/wiki/Observer_pattern ) so your model objects throw events nearly for anything and an observer decides to cache data to RAM, to fill data or to store data to the disk.
This strongly enhances the solid/closed principle. You should never change your model if the thing you change is not domain-related. For example adding a new way of storing to a new type of database, should require zero edition on your model classes.
You can see an example of this in the following image. In it, I highlight a bundle named "TurnBasedBundle" that is like the core functionality for every game that is turn-based, despite if it has a board or not. You can see that the bundle only has Model and Tests.
Every game has a ruleset, players, and during the game, the players express the desires of what they want to do.
In the Game object, the instantiators will add the ruleset (poker? chess? tic-tac-toe?). Caution: what if the ruleset I want to load does not exist?
When initializing, someone (maybe the /start controller) will add players. Caution: what if the game is 2-players and I add three?
And during the game the controller that receives the players movements will add desires (for example, if playing chess, "the player wants to move queen to this tile" -which may be a valid, or not-.
In the picture you can see those 3 actions under control thanks to the events.
You can observe that the bundle has only Model and Tests.
In the model, we define our 2 objects: Game, and the GameManager, to get instances of Game objects.
We also define Interfaces, like for example the GameObserver, so anyone willing to receive the Game events should be a GameObserver folk.
Then you can see that for any action that modifies the state of the model (for example adding a player), I have 2 events: PRE and POST. See how it works:
Someone calls the $game->addPlayer( $player ) method.
As soon as we enter the addPlayer() function, the PRE event is raised.
The observers then can catch this event to decide if a player can be added or not.
All PRE events should come with a cancel passed by reference. So if someone decides this is a game for 2 players and you try to add a 3rd one, the $cancel will be set to true.
Then you are again inside the addPlayer function. You can check if someone wanted to cancel the operation.
Do the operation if allowed (ie: mutate the $this-> state).
After the state has been changed, raise a POST event to indicate the observers that the operation has been completed.
In the picture you see three, but of course it has a lot lot more. As a rule of thumb, you will have nearly 2 events per setter, 2 events per method that can modify the state of the model and 1 event for each "unavoidable" action. So if you have 10 methods on a class that operate on it, you can expect to have about 15 or 20 events.
You can easily see this in the typical simple text box of any graphyc library of any operating system: Typical events will be: gotFocus, lostFocus, keyPress, keyDown, keyUp, mouseDown, mouseMove, etc...
Particularly, in your example
The Person will have something like preChangeAge, postChangeAge, preChangeName, postChangeName, preChangeLastName, postChangeLastName, in case you have setters for each of them.
For long-living actions like "person, do walk for 10 seconds" you maybe have 3: preStartWalking, postStartWalking, postStopWalking (in case a stop of 10 seconds cannot be programatically prevented).
If you want to simplify, you can have two single preChanged( $what, & $cancel ) and postChanged( $what ) events for everything.
If you never prevent your changes to happen, you can even just have one single event changed() for all and any change to your model. Then your entity will just "copy" the model properties in the entity properties at every change. This is OK for simple classes and projects or for structures you are not going to publish for third-party consumers, and saves some coding. If the model class becomes a core class to your project, spending a bit of time adding all the events list will save you time in the future.
Step 5: Catch the events from the data layer.
It is at this point that your data-layer bundle enters in action!!!
Make your data layer an observer of your model. When the model Changes its internal state then make your Entity to "copy" that state into the entity state.
In this case, the MVC acts as expected: The Controller, operates on the Model. The consequences of this are still hidden from the controller (as the controller should not have access to Doctrine). The model "broadcasts" the operation made, so anyone interested knows, which in turn triggers that the data-layer knows about the model change.
Particularly, in your project
The Model/Person object will have been created by the PeopleManager. When creating it, the PeopleManager, which is a service, and therefore can have other services injected, can have the ObjectStorageManager subsystem handy. So the PeopleManager can get the Entity/People that you reference in your question and add the Entity/People as an observer to Model/Person.
In the Entity/People mainly you substitute all the setters by event catchers.
You read your code like this: When the Model/Person changes its LastName, the Entity/People will be notified and will copy the data into its internal structure.
Most probably, you are tempted to inject the entity inside the model, so instead of throwing an event, you call the setters of the Entity.
But with that approach, you 'break' the Open-Closed principle. So if at any given point you want to migrate to MongoDb, you need to "change" your "entities" by "documents" in your model. With the observer-pattern, this change occurs outside the model, who never knows the nature of the observer beyond that is its a PersonObserver.
Step 6: Unit test everything
Finally, you want to unit test your software. As this pattern I have explained overcomes the anti-pattern that you discovered, you can (and you should) unit-test the logics of your model independently of how that is stored.
Following this pattern, helps you to go towards the SOLID principles, so each "unit of code" is independent on the others. This will allow you to create unit-tests that will test the "logics" of your Model without writing to the database, as it will inject a fake data-storage layer as a test-double.
Let me use the game example again. I show you in the image the Game test. Assume all games can last several days and the starting datetime is stored in the database. We in the example currently test only if getStartDate() returns a dateTime object.
There are some arrows in it, that represent the flow.
In this example, from the two injecting strategies I told you, I choose the first one: To inject into the Game model object the services it needs (in this case a BoardManager, PieceManager and ObjectStorageManager) and not to inject the GameManager itself.
First, you invoke phpunit that will call look for the Tests directory, recursively in all the directories, finding classes named XxxTest. Then will desire to invoke all the methods named textSomething().
But before calling it, for each test method it calls the setup().
In the setup we will create some test-doubles to avoid "real access" to the database when testing, while correctly testing the logics in our model. In this case a double of my own data layer manager, ObjectStorageManager.
It is assigned to a temporary variable for clarity...
...that is stored in the GameTest instance...
...for later use in the test itself.
The $sut (system under test) variable is then created with a new command, not via a manager. Do you remember that I said that tests were an exception? If you use the manager (you still can) here it is not a unit-test, it's an integration test because tests two classes: the manager and the game. In the new command we fake all the dependencies that the model has (like a board manager, and like a piece manager). I am hardcoding GameId = 1 here. This relates to data-persistance, see below.
We then may call the system under test (a simple Game model object) to test its internals.
I am hardcoding "Game id = 1" in the new. In this case we are only testing that the returned type is a DateTime object. But in case we want to test also that the date that it gets is the proper one, we can "tune" the ObjectStorageManager (data-persistance layer) mock to return whatever we want in the internal call, so we could test that for example when I request the date to the data-layer for game=1 the date is 1st-jun-2014 and for game=2 the date is 2nd-jun-2014. Then in the testGetStartDate I would create 2 new instances, with Ids 1 and 2 and check the content of the result.
Particularly, in your project
You will have a Test/Model/PersonTest unit test that will be able to play with the logics of the person, and in case of needing a person from the database, you will fake it thru the mock.
In case you want to test the storing of the person to the database, it is enough that you unit-test that the event is thrown, no matter who listens to it. You can create a fake listener, attach to the event, and when the postChangeAge happens mark a flag and do nothing (no real database storage). Then you assert that the flag is set.
In short:
Do not confuse logics and data-persistance. Create a Model that has nothing to do with entities, and put all the logics in it.
Do never use new to get your models from any consumer. Use factory services instead. Special attention to avoid news in controllers and commands. Exception: The unit-test is the only consumer that can use a new.
Inject the services you need in the Model via the factory, which in turn receives it from the services.yml configuration file.
Throw events for everything. When I say everything, means everything. Just imagine you observe the model. What would you like to know? Add an event for it.
Catch the events from controllers, views, commands and from other parts of the model, but, specially, catch them in the data-storage layer, so you can "copy" the object to the disk without being intrusive to the model.
Unit test your logics without depending on any real database. Attach the real database storage system in production and attach a dummy implementation for your tests.
Seems a lot of work. But it is not. It is a matter of getting used to it. Just think about the "objects" you need, create them and make the data-layer be "monitors" of your objects. Then your objects are free to run, decoupled. If you create the model from a factory, inject any needed service in the model to the model, and leave the data alone.
Edit apr/2016 - Separating Domain from Persistance
All occurences of the word entity in this answer are referring to the "doctrine entities" which is what causes confusion to the majority of coders, between the model layer and the persistance layer which should be always different.
Doctrine is infrastructure, so doctrine is outside the model by definition.
Doctrine has entities. So, by definition, then doctrine entities are also outside the model.
Instead, the increasing popularity of the DDD building blocks makes a need to clarify even more my answer, as DDD uses the word Entity within the model too.
Domain entities (not Doctrine entities) are similar to what I refer in this answer to Domain objects.
In fact, there are many types of Domain objects:
Domain entities (different from the Doctrine entites).
Domain value objects (could be thought similar to basic types, with logic).
Domain events (also distinct from those Symfony events and also different from the Doctrine events).
Domain commands (different from those Symfony command line controller-like helpers).
Domain services (different from the Symfony framework services).
etc.
Therefore, take all my explanation as this: when I say "Entities are not model objects" just read "Doctrine entities are not Domain entities".
Edit jun/2019 - CQRS+ES analogy
Ancients already used persistant history methods to recod things (for example placing marks on a stone to register transactions).
Since a decade long the CQRS+ES approach (Command Query Responsability Segregation + Event Sourcing) in programming has been growing in popularity, bringing that idea of "the history is immutable" to the programs we code and today many coders think of separating the command side vs the query side. If you don't know what I'm talking about, no worries, just skip the next paragraphs.
The growing popularity of CQRS+ES in the last 3 or 4 years makes me think to consider a comment here and how it relates to what I answered here 5 years ago:
This answer was thought as 1 single model, not a write-model and a read-model. But I'm happy to see many overlapping ideas.
Think of the PRE events, I mention here, as the "commands and the write-model". Think of the POST events as the "Event Sourcing part going towards the read-model".
In CQRS you can easily find that "commands can be accepted or not" in function of the internal state. Usually one implements them throwing exceptions but there are other alternatives there, like answering if the command was accepted or not.
For example, in a "Train" I can "set it to X speed". But if the state is that the train is in a rail that cannot go further 80Km/h, then setting it to 200 should be rejected.
This is ANALOGOUS to the cancel boolean passed by reference where an entity could just "reject" something PRIOR to its state change.
Instead the POST events do not carry the "cancel" event and are thrown AFTER the state change happened. This is why you could not cancel them: They talk about the "state change that actually occurred" and therefore it cannot be cancelled: It aleady happened.
So...
In my answer of 2014, the "pre" events match with the "Command acceptance" of the CQRS+ES systems (the command can be accepted or rejected), and the "post" events match the "Domain events" of the CQRS+ES systems (it just informs that the change actually already happened, do whatever you want with that information).
You already mentioned a very good point. Instances of class Person are not the only thing that can have an age. BlogArticles can also age along with many other types. If you're using PHP 5.4+ you can utilize traits to add little pieces of functionality instead of having service objects from the container (or maybe you can combine them).
Here is a quick mockup of what you could do to make it very flexible. This is the basic idea:
Have one age calculating trait (Aging)
Have a specific trait which can return the appropriate field ($birthdate, $createdDate, ...)
Use the trait inside your class
Generic
trait Aging {
public function getAge() {
return $this->calculate($this->start());
}
public function calculate($startDate) { ... }
}
For person
trait AgingPerson {
use Aging;
public function start() {
return $this->birthDate;
}
}
class Person {
use AgingPerson;
private $birthDate = '1999-01-01';
}
For blog article
// Use for articles, pages, news items, ...
trait AgingContent {
use Aging;
public function start() {
return $this->createdDate;
}
}
class BlogArticle {
use AgingContent;
private $createDate = '2014-01-01';
}
Now you can ask any instance of the above classes for their age.
echo (new Person())->getAge();
echo (new BlogArticle())->getAge();
Finally
If you need type hinting traits won't do you any favors. In that case you will need to provide an interface and let every class that uses the trait implement it (the actual implementation is the trait but the interface enables type hinting).
interface Ageable {
public function getAge();
}
class Person implements Ageable { ... }
class BlogArticle implements Ageable { ... }
function doSomethingWithAgeable(Ageable $object) { ... }
This may seem like a lot of hassle when in reality it's much easier to maintain and extend this way.
A big part is that there is no easy way to inject dependencies when using the database.
$person = $personRepository->find(1); // How to get the age service injected?
One solution might be to pass the age service as an argument.
$ageCalculator = $container('age_service');
$person = $personRepository->find(1);
$age = $person->calcAge($ageCalculator);
But really, you would probably be better off just adding the age stuff to your Person class. Easier to test and all that.
It sounds like you might have some output formatting going on? That sort of thing should probably be done in twig. getAge should really just return a number.
Likewise, your date of birth really should be a date object and not a string.
You are right, it's generally discouraged. However, there are several approaches how you can extend the functionality of an entity beyond the purpose of a data container. Of course, all of them can be considered (more or less) bad practice … but somehow you gotta do the job, right?
You can indeed create an AbstractEntity super class, from which all other entities inherit. This AbstractEntity would contain helper methods that other entities may need.
You can work with custom Doctrine repositories, if you need an entity context to work with an entity manager and return “more special” results than what the common getters would give you. As you have access to the entity manager in a repository, you can perform all kinds of special queries.
You can write a service that is in charge of the entity/entities in question. Downside: you cannot control that other parts of your code (or other developers) know of this service. Advantage: There's no limit to what you can do, and it's all nicely encapsuled.
You can work with Lifecycle Events/Callbacks.
If you really need to inject services into entities, you could consider setting a static property on the entity and only set it once in a controller or a dedicated service. Then you don't need to take care on each initialization of an object. Could be combined with the AbstractEntity approach.
As mentioned before, all of these are have their advantages and disadvantages. Pick your poison.

Flex: Additional label in ButtonBarButton

I'm trying to extend ButtonBarButton to include an additional label that shows the number of updates for the respective box in a viewstack (which is the tabbar's dataProvider).
I can get the additional label (named indicatorLabel) to read an initial value from data, but I can't get it to update automatically like the actual "label" attribute. My understanding was that you could bind to the data object, but that doesn't appear to be the case.
The box that is used in the viewstack has an attribute called _indicator
[Bindable]
public var _indicator:String;
Which I know is updating properly because I can see it updating in the box (which also has a label bound to it). It appears to just not update the buttonbarbutton.
My buttonbarbutton class has the following (where init() is called in creationComplete
[SkinPart]
public var indicatorLabel:spark.components.Label;
private function init():void
{
indicatorLabel = data._indicator;
addEventListener("dataChange", onDataChangeHandler);
}
private function onDataChangeHandler(e:Event):void
{
trace(e.target.label + ' ' + e.target._indicator);
}
I'm guessing my assumptions for either databinding or the data obj that gets passed to the button are incorrect. Any help is appreciated.
I have answered a question here just a few days ago that is closely related to this one. It's a bit more abstract, but it should answer yours too. Have a look at Flex : Communicate between the skin and the data model?
As for your additional question about performance improvement: you just have to keep in mind that whenever you use binding, the compiler will generate some event listeners to listen for changes in the data. Of course that's not an issue with a one-off component or even with a bunch of instances, but it may become one if you have a List with thousands of components that all use binding. First of all the garbage collector won't clean these components up so easily when they're no longer needed and secondly - depending on your implementation - thousands of events may be firing at once.
bottom line: you could consider the commitProperties() approach performance tuning, hence you shouldn't consider it until you actually run into a performance issue.
on the other hand from an architectural point of view: that approach allows for a cleaner separation of the component and its skin. With the hostComponent / binding approach you could say the skin knows too much: it has to know about its host component and its properties. While the other one allows you to have a completely 'dumb' skin. So again I tend to use binding with one-off components and commitProperties() with highly reusable ones.
In the end it's all a trade-off (because the 'clean' way is more complex and more work) and it's up to you to make a weighed decision for each particular situation.

Communication between Flex module and Application

Ok, modules in Flex are popular but I have no idea why documentation and examples on the different uses of Flex modules can be so scarce.
Anyway, for this question, I will take the classic Employee/Department example. I have a main.mxml that contains an mx:TabNavigator. Each tab is loaded by an s:ModuleLoader.
Tables: Employees {empID,empName,deptID}, Deparments {deptID,deptName}
The Tab Navigator contains only one tab (for our example) called Employee. I have an Employee.mxml module. In that module, I have a datagrid that is populated with Employee details. I use the getEmployees($deptID) function. This function, as you may guess, returns me an array of Employees who work in a particular department.
Outside the TabNavigator, I have a departmentDropDownList that is populated with departments.deptName.
My objective is to load the Employee module when I select a particular department from the DropDownList. I have a changeHandler for the DropDownList that can give me the deptID.
protected function departmentDropDownList_changeHandler(event:IndexChangeEvent):void
{
MyDeptID=departmentDropDownList.selectedItem.deptID;
//var ichild:*=employeeModule.child as IModuleInfo;
}
Now, the million dollar question is: How do I pass this deptID to the Employees module. The latter has an employee_creationCompleteHandler that calls getEmployees(deptID):
protected function EmployeesDg_creationCompleteHandler(event:FlexEvent):void
// I only need to get the deptID from the departmentDropDownList outside the Employee module.
// If I could create a global variable deptID, that would be great!
getEmployeessResult.token=employeeService.getEmployeess(deptID);
}
I have attempted to use [Bindable] variables but without success.
I would appreciate your suggestions.
You can't really guarantee that the deptID will be set when creationComplete runs--it sounds like you're waiting for a server result--so this is probably not the best way to handle it.
One of the things you need to be careful of is directly referencing the full Module Class from the main Application, because the point of modules is that you should not compile in the module Class into the main Class (to reduce file size/load times).
So what you might want to do is create an Interface. This creates a "contract" between the main application and the Module without carrying all the implementation code with it. That might look something like this
public interface IEmployeeModule {
function set deptID(value:int):void;
}
Then, your Module might have code that's something like this:
protected var _deptID:int;
public function set deptID(value:int):void {
_deptID = value;
var token:AsyncToken=employeeService.getEmployeess(deptID);
token.deptID = value;//in case department id changes, you can determine if you still care
}
Note that, though global variables seem like a wondermous idea when your project is small, they are a very bad habit to get into. It can be almost impossible to repair a project that starts out with these and then grows to the point that no one can figure out exactly which of the hundreds or thousands of Classes that have access to a variable are changing it in the wrong way at the wrong time.
You ESPECIALLY don't want to use global variables with Modules, as they can cause really bad problems when the modules start fighting over the definition.
We solved this problem with the use of Cairngorm v2. Think of it as a message bus for ActionScript, one of several. In your departmentDropDownList_changeHandler method we would create a DeptChanged event with the ID as the payload, and send it on the bus to any and all subscribers to that message type. It worked pretty well for us, and made things more event driven, which in some circles is considered a good thing in itself.
#J_A_X I haven't had good luck with using Robotlegs out of the box with Modules. It seems that something goes wonky with the security contexts, even though it shouldn't. I had to use Joel Hooks' ModuleContext to make it work right, even though my needs were fairly basic.

Grails - Removing an item from a hasMany association List on data bind?

Grails offers the ability to automatically create and bind domain objects to a hasMany List, as described in the grails user guide.
So, for example, if my domain object "Author" has a List of many "Book" objects, I could create and bind these using the following markup (from the user guide):
<g:textField name="books[0].title" value="the Stand" />
<g:textField name="books[1].title" value="the Shining" />
<g:textField name="books[2].title" value="Red Madder" />
In this case, if any of the books specified don't already exist, Grails will create them and set their titles appropriately. If there are already books in the specified indices, their titles will be updated and they will be saved. My question is: is there some easy way to tell Grails to remove one of those books from the 'books' association on data bind?
The most obvious way to do this would be to omit the form element that corresponds to the domain instance you want to delete; unfortunately, this does not work, as per the user guide:
Then Grails will automatically create
a new instance for you at the defined
position. If you "skipped" a few
elements in the middle ... Then Grails
will automatically create instances in
between.
I realize that a specific solution could be engineered as part of a command object, or as part of a particular controller- however, the need for this functionality appears repeatedly throughout my application, across multiple domain objects and for associations of many different types of objects. A general solution, therefore, would be ideal. Does anyone know if there is something like this included in Grails?
removeFrom*
Opposite of the addTo method in that it removes instances from an association.
Examples
def author = Author.findByName("Stephen King")
def book = author.books.find { it.title = 'The Stand' }
author.removeFromBooks(book)
Just ran into this issue myself. It's easy to solve. Grails uses java.util.Set to represent lists. You can just use the clear() method to wipe the data, and then add in the ones you want.
//clear all documents
bidRequest.documents.clear()
//add the selected ones back
params.documentId.each() {
def Document document = Document.get(it)
bidRequest.documents.add(document)
log.debug("in associateDocuments: added " + document)
};
//try to save the changes
if (!bidRequest.save(flush: true)) {
return error()
} else {
flash.message = "Successfully associated documents"
}
I bet you can do the same thing by using the "remove()" method in the case that you don't want to "clear()" all the data.
For a good explanation of deleting a collection of child objects with GORM have a look at the Deleting Children section of this blog post - GORM gotchas part 2
It's recommended reading, as are parts 1 and 3 of the series.
I am just starting to learn Grails myself and saw your question as an interesting research exercise for me. I do not think you can use the conventional data binding mechanism - as it fills in the blanks using some kind of Lazy map behind the scenes. So for you to achieve your goal your "save" method (or is it a function?) is unlikely to contain anything like:
def Book = new Book(params)
You need a mechanism to modify your controller's "save" method.
After some research, I understand you can modify your scaffolding template which is responsible for generating your controller code or runtime methods. You can get a copy of all the templates used by Grails by running "grails install-templates" and the template file you would need to modify is called "Controller.groovy".
So in theory, you could modify the "save" method for your whole application this way.
Great! You would think that all you need to do now is modify your save method in the template so that it iterates through the object entries (e.g. books) in the params map, saving and deleting as you go.
However, I think your required solution could still be quite problematic to achieve. My instinct tells me that there are many reasons why the mechanism you suggest is a bad idea.
For one reason, off the top of my head, imagine you had a paginated list of books. Could that mean your "save" could delete the entire database table except the currently visible page? Okay, let us say you manage to work out how many items are displayed on each page, what if the list was sorted so it was no longer in numerical order - what do you delete now?
Maybe multiple submit buttons in your form would be a better approach (e.g. save changes, add, delete). I have not tried this kind of thing in Grails but understand actionSubmit should help you achieve multiple submit buttons. I certainly used to do this kind of thing in Struts!
HTH
I'm just running into this same issue.
My application's domain is quite simple: it has Stub objects which have a hasMany relationship with Header objects. Since the Header objects have no life of their own, they're entirely managed by the Stub controller and views.
The domain class definitions:
class Stub {
List headers = new ArrayList();
static hasMany = [headers:Header]
static mapping = {headers lazy: false}
}
class Header {
String value
static belongsTo = Stub
}
I've tried the "clear and bind" method but the end result is that the "cleared" objects are left over in the database and grails will just create new instances for the ones that were not removed from the relationship. It does seem to work from an user's perspective, but it will leave lots of garbage objects in the database.
The code in the controller's update() method is:
stubInstance.headers.clear()
stubInstance.properties = params
An example: while editing the -many side of this relationship I have (for a given Stub with id=1):
<g:textField name="headers[0].value" value="zero" id=1 />
<g:textField name="headers[1].value" value="one" id=2 />
<g:textField name="headers[2].value" value="two" id=3 />
in the database there are 3 Header instances:
id=1;value="zero"
id=2;value="one"
id=3;value"two"
after removing header "one" and saving the Stub object the database will have headers:
id=1;value="zero"
id=2;value="one"
id=3;value"two"
id=4;value="zero"
id=5;value="two"
and the Stub object will now have an association with Headers with id=4 and id=5...
Furthermore, without the clearing of the list, if an index is not present in the submitted request.headers list, on data binding grails will keep the existing object at that location unchanged.
The solution that occurs to me is to bind the data, then check the Stub's headers for elements that are not present in the submitted list and remove them.
This looks like a pretty simple scenario, isn't there any built-in functionality to address it?
It's a bit overkill to have to write your own synchronization logic for maintaining relationships, especially when the quirks that make it non-trivial are caused by grails itself.
What about deletion, shouldn't the clear()'ed elements be gone from the database? Am I missing something in the relationship or domain object definitions?
class Stub {
List headers = new ArrayList();
static hasMany = [headers:Header]
static mapping = {
headers lazy: false
**headers cascade: "all-delete-orphan"**
}
}
class Header {
String value
static belongsTo = Stub
}
I have added the cascade property on the owning side of relationship and Now if you try to save the stub, it will take care of removing deleted items from the collection and delete them from the DataBase.

Handling client-side domain object state in a presentation model

I'm currently building the client side of a Flex/PHP project using the Presentation Model pattern.
What I'm trying to achieve:
I currently have a view displaying non-editable information about a domain object called Node. Depending on if the Node is editable and the user has the right privileges, an additional view becomes available where it's possible to make changes to this object. Any changes made are only committed to the server once the user decides to "Save Changes". If changes are made to a NodeA and the user navigates away to a different NodeB without saving them, NodeA is reverted to its original state.
Design:
I have a PM for the info view holding a reference to the current Node. The PM for the edit view is extended from this info PM, adding methods to make changes to the wrapped Node object. Both PMs has the same Node reference injected into them and all fields in the info/edit views are bound to the Node via their PMs.
The problem:
When the user makes changes to NodeA but doesn't commit them, I can't seem to think of an elegant solution to revert back to the original state. Basically, what I've thought of so far is to hold separate value copies on the edit PM, either clone-creating a new Node reference or through an identical set of Node properties. Of these two the former seems like the better idea because the Node already houses domain logic, but I wonder whether creating clones of unique domain objects is a bad practice, even if it's used in a limited scope.
I handle similar cases by storing the original data in an XML property of the Value Object ("VO"), and reset all of the other property values when the VO is needed.
So, when it is first needed to be viewed, I go get the XML:
<Node>
<prop1>value</prop1>
<prop2>value</prop2>
<prop3>value</prop3>
<prop4>value</prop4>
</Node>
When I retrieve the XML, in my result handler, the first thing I do is create an instance of my VO, and set the XML property, and then call a public function in a separate class to set the VO's properties:
private function getNodeResultHandler(event:ResultEvent):void
{
var myNode:Node = new Node();
myNode.xmlData = new XML(event.result);
nodeUtils.setNodeProperties(myNode);
}
public class nodeUtils
{
public function setNodeProperties(node:Node):void
{
var nodeXmlData:XML = node.xmlData;
myNode.prop1 = nodeXmlData.prop1;
myNode.prop2 = nodeXmlData.prop2;
myNode.prop3 = nodeXmlData.prop3;
myNode.prop4 = nodeXmlData.prop4;
}
}
Then, any time you switch your view to edit mode, you call that same function to reset the properties to the values stored in the XML.
The only other thing you need to do is reset that XML any time the user commits changes to the VO. I usually handle this by passing back the VO's data in the same format on a Save and Get, and then saving the XML just as above.
I usually do this in a Cairngorm MVC application, so I have event/command chains to handle all of this, but you can put this functionality in any number of classes, or in the VO class itself, whichever is easiest for you to maintain.
Each view should have it's own instance of your Presentation Model class. Just maintain it in memory if the user has not saved it when moving to another view. Cloning accomplishes basically the same thing through a more convoluted process.

Resources