Symfony2: Difference between those metodology "Embedded Form" and "Data Transformer" - forms

Consider the following scenario
We have a simple database that involves two entities: user and category.
For our hypothesis let's say that a user can have only a type of category and a category can be associated with n users.
Now, consider a web page where a user - say ROLE_ADMINISTRATOR - could edit user table and associate them to a different one category.
As far I know (and I'm still new to symfony in general) if I use Doctrine and symfony2 in tandem, with - let's say - annotation method, i'll have two entity (php classes).
Embedded form
I will create a form that will show the user and, for show - and persist, of course! - also his category I "choose" to follow the "embedded form" strategy.
Having said that the entity has been created, i'll have to create a form for category (suppose that into formBuilder I'll add only id attribute of the category).
After that I have to add to formBuilder of UserType class the previous form and, with "some kind of magic" the form will render (after the appropriate operations) as magic and just as magically, when i'll post it (and bind, and so on) back all the informations will be persists onto database
Data Transformers
A.K.A. trasnform an input of a form into an object and vice versa.
In that way I'll have to define a - let's say - CategorySelectorType that into his builder, will add a Class (service ?) that will do those transformations.
Now we define the data transformer itself that will implement the DataTransofmerInterface (with his method and so on...)
The next step will be register that entity into services and add into UserType the form that will use this service.
So I don't understand any "strong" difference between those two metodology but "reusability" of the service. Somebody can offer me a different point of view and explain me the differences, if any?

A data transformer does not replace a embedded form, it rather enhances forms and wraps data transformation nicely.
The first sentence on the cookbook page about Data Transformers sums it up nicely:
You'll often find the need to transform the data the user entered in a
form into something else for use in your program.
In your example above, you could add a drop-down list of categories so the admin can select one for the given user. This would be done using a embedded form. As the category field is the id of an existing category, there is no need to transform the data.
For some reason you now want the admin to be able to enter a free text of the category. Now you need to do some tranformation of the text into the object in question. Maybe you want him to be able to either add a new or select a current category with this text field. Both is possible by using a data transformer which takes the text and searches for the category. Depending on your needs, not existing categories can be created and returned.
Another use case is when a user enters data which needs to be modified in some way before storing them. Let's say the user enters a street, house number and city but you want to store the coordinates instead.
In both cases it doesn't matter if you embed the form into another!
Could you do that in your controller? Of course. Is it a good idea to do such things in the controller? Probably not, as you have a hard time testing (while doing it in the transformer let you unit test the transformation nicely) or reusing it.
UPDATE
Of course it is possible to place the transformation code someplace else. The user object itself is not a good place, as the model should not know about the entity manager, which is needed to do the transformation.
The user type would be possible, but this means that it gets tied to the entity manager.
It all adds up to the very powerfull concept of Separation of concerns, which states that one class should only do one thing to make it maintainable, resuable, testable and so on. If you follow this concept, than it should be clear that data transformation is a thing on its own and should be threated as such. If you don't care, you may not need the transformation functionality.

Related

UML sequence for validation before saving

I'm new to UML but I'm tasked to draw some UML diagrams that describe some complex parts of our system.
One of these parts is the saving of data in the db, and the steps said data goes through before it can actually be saved.
These are roughly the steps involved:
User wants to save
App validates that all mandatory fields have values set
If not valid, app shows a message. If valid, app sends a post request
The controller maps the dto to the domain model object and passes it to the service layer
Service layer validates the model according to business rules. If not valid, throws a validation exception
If valid, model moves down to the data access layer, where EF is used to commit the changes to the db
On trying to commit, EF might throw a validation exception (mapping) or database exception (bubbled up from the db itself)
If commit succeeds, the model is passed to the controller which maps it back to its dto counterpart and displayed to the user
If validation or database exception is thrown, these are displayed to the user
So far this is what I came up with:
Is this good enough to display the above steps or might there be improvements to the diagram?
In sequence diagrams we show the interaction between classes or objects. before drawing sequence diagram we need to identify the classes and their methods(behaviours). In sequence diagrams there are three type of classes.
boundry class
control class
Entity class
Boundry classes represents the views of the system(user interfaces).
Entity classes show the table of the database(Entities)
Control classes stay between boundry classes and Entity classes.And passes messages among them.
In Your diagram I think database should not be a class name. So you
can't define it in the sequence diagram.(you can define related class for particular table)
you need to specify the data you are passing to other classes through
a method. for example:
save(user_name,age)
You can display user as a actor rather than displaying as a class.
current diagram doesn't show the conditions of the system(if else
condition).You can use "alt" to show the conditions.
when you are passing messages between classes the method name should have been defined in the receiving class.
If you put something on a sequence diagram then it means it has to be applied unconditionally (i.e. on each run you need to have ValidationErrors message and DatabaseErrors message which probably isn't something you want).
Actually you don't have a positive path on your diagram (the "OK" from DataAccess Layer comes after receiving 2 Exceptions, same for return from Database to Entity Framework .
Moreover OccurenceEvent should always start at the message/signal reception. On your diagram some of those begin without any actual triggers.
Read about Fragments, especially Combined Fragments (17.6/17.6.3.3 in UML specification, however I suggest some more user friendly type of documentation, like uml-diagrams.org or some books about UML).
Also I'm not sure if SO is the best place for this type of questions. It should rather be put on some discussion panel (forum) as you don't have a specific problem, but would rather like to validate your diagram.

VBA Excel Best Practices for using Forms and Classes together?

I am new to using classes and would like to learn smart ways of integrating them with forms. Specifically, when you enter data into a form, should that form be tightly linked with a class and how?
Let's use a simple example. John is a collector of all kinds of cards: baseball cards, Pokemon cards, etc. He keeps his card list database stored in Excel worksheets and manages them using forms. There are forms for entering new cards and modifying their status in his collection, and there are also forms and functions for analyzing his data.
So he might have a clsBaseball, a clsPokemon, a clsAlbum and a clsSalesRecord. He also has forms for entering and modifying data and other types of analysis forms that compare cards, calculate stats for various teams and time periods, etc.
When John clicks the "New Baseball Card" button, his frmBaseball pops up.
He enters baseball card data
He clicks Update
The form is validated
The data is saved onto the worksheet
At any point in the above process is clsBaseball used? I can see how the class would be used to load up all data in service of fancy sorting or statistical routines, but is it actually used during the entry phase such that the fields on the form have a direct effect on an instance of clsBaseball?
It depends on how robust your requirements are. If you're just prototyping something then tightly binding your code to your form is fine. If however you want to build a more flexible, robust and extensible application, then modelling your data structure in classes, encapsulating your functionality in objects is the way to go.
Classes enable you to model real world things and they facilitate their implementation in a logically separated tiered architecture. In your case your form provides the presentation layer, your classes provide the application tier, and your excel sheets provide the data tier (normally a database) - this is 3 tier.
So, in your example I would model your data in classes, as you have done, but then if I required functionality requiring all my clsBaseball objects, I would have managing classes for each object. These managing classes contain a collection of your clsBaseball objects and allow you to implement behaviour that requires a collection of objects. For example, you would implement your update method in clsBaseball, but you would implement CalculateStats in the clsBaseballs managing class, you could also call the update methods for all your clsBaseball objects by iterating over the collection of clsBaseball in (managing class) clsBaseballs.
In answer to your questions:
At any point in the above process is clsBaseball used?
1) He enters baseball card data:
You maybe instantiate an instance of clsBaseball, but perhaps not yet
2) He clicks update:
You instantiate a new instance of clsBaseball (or use the existing one), pass through the user entered values and call clsBaseball's update method. In this way you encapsulate the clsBaseball behaviour.
3) The form is validated:
This would occur before the clsBaseball updates the datastore. So you would probably have a validation method in clsBaseball that is called before any data is updated. Any errors can be passed back up to the presentation layer (your form). Or you could just validate in the form (though having any business logic in your presentation layer is frowned upon because you might want to switch out your presentation layer for something else, please see the MVC/MVP patterns).
4) The data is saved onto the worksheet:
This is done by clsBaseball by the update method.
As for your fancy sorting or statistical routines, you could get this data from your managing classes which, because they contain collections of your objects are perfectly setup to analyse all your clsBaseball instances. All of this functionality is nicely encapsulated, there is no repetition (DRY) and anyone coming newly to the code will be able to figure out what's going on.
I answered a question a little while ago re how to structure data in MS Access, the answer includes examples of a class and managing class: MS ACCESS 2003 triggers (Query Event), and Excel import

Best practice for MVC 4 Edit Views and "Hidden" parameters

I have recently added some fields for auditing purposes to existing models in an MVC 4/ Entity project. I don't need these fields to be displayed on the edit page. However, they are required fields on the model.
As it stands, the edit page still works, but on the controller side, the ModelState.IsValid check fails because the required fields that are actually set on the item are not output to the view and therefore not re-submitted when the edit page is submitted.
Is there an easy, built in way to rectify this, or if not, which of the following is best practice for this scenario? Are there more options?
1) Set up hidden fields on the view to hold the information (Not a fan of this option, passes data around too much)
2) in the controller, on submit, first load the model by ID, then set each individual parameter based on the fields present on the view (Seems like extra unnecessary work)
3) Create a constructor for the model that takes itself as a parameter and pulls any non-default values and returns a new object. Basically a merge. (Best I think, still a lot of extra work)
4) ???
Best practice is to not use your domain model inside the views. Create a view model class that contains only the id and the fields you want in the view. Pass this model to your view. Change the parameter type of the form submit action to match your new view model. This will then pass the model validation without using hidden fields. In your action method, you can then retrieve the object from the database using the id property of the view model class and update fields as required.
Hope that makes sense.
I prefer to do the 2nd option as long as I can get the existing object with a single query or db call. This lets me to keep my view clean(no hidden fields for all those other properties) and use the existing update method which updates the domain model.
Look into your code. If the update method is making updates in lot of other places(many other tables) which is really not needed, then you could possibly write a short version of the update method which updates only the relevant parts ( ex: UpdateContactDetails).

Core Data object graph design decision

I am designing an app which tracks data on Game objects. Each Game has a name, a date and other attributes. The problem I am having arises because I want the user to be able to add more names (for example) to pick from in the application. (in this case from a UITableView). So the user is presented with a list of names to choose from, and if the one they want is not in the list, they can add one to the list.
My solution is that I currently have a second entity called GameName so that I can show the user a list of those game names to pick from when they are adding a new Game. I just call an NSFetchRequest on all the GameName objects and display them in the UITableView. There doesn't have to be a Game object created yet to do this.
My dilemma is that I want to know if this is a good practice. It seems that if I do it this way, I will end up having a lot of entities with just one attribute, for the sake of allowing the user to pick from and add to a customizable list.
I hope this makes sense. I can clarify anything upon request.
Your approach is fine, and is commonly used in database design. The entity you want to add is called a "domain table" in databases. See this page, in particular this paragraph:
In a normalized data model, the reference domain is typically specified in a reference table. Following the previous example, a Gender reference table would have exactly two records, one per allowed value—excluding NULL. Reference tables are formally related to other tables in a database by the use of foreign keys.
Of course, you probably want to have an optional relationship between the GameName and Game entities.

Entity Framework and Encapsulation

I would like to experimentally apply an aspect of encapsulation that I read about once, where an entity object includes domains for its attributes, e.g. for its CostCentre property, it contains the list of valid cost centres. This way, when I open an edit form for an Extension, I only need pass the form one Extension object, where I normally access a CostCentre object when initialising the form.
This also applies where I have a list of Extensions bound to a grid (telerik RadGrid), and I handle an edit command on the grid. I want to create an edit form and pass it an Extension object, where now I pass the edit form an ExtensionID and create my object in the form.
What I'm actually asking here is for pointers to guidance on doing this this way, or the 'proper' way of achieving something similar to what I have described here.
It would depend on your data source. If you are retrieving the list of Cost Centers from a database, that would be one approach. If it's a short list of predetermined values (like Yes/No/Maybe So) then property attributes might do the trick. If it needs to be more configurable per-environment, then IoC or the Provider pattern would be the best choice.
I think your problem is similar to a custom ad-hoc search page we did on a previous project. We decorated our entity classes and properties with attributes that contained some predetermined 'pointers' to the lookup value methods, and their relationships. Then we created a single custom UI control (like your edit page described in your post) which used these attributes to generate the drop down and auto-completion text box lists by dynamically generating a LINQ expression, then executing it at run-time based on whatever the user was doing.
This was accomplished with basically three moving parts: A) the attributes on the data access objects B) the 'attribute facade' methods at the middle-tier compiling and generation dynamic LINQ expressions and C) the custom UI control that called our middle-tier service methods.
Sometimes plans like these backfire, but in our case it worked great. Decorating our objects with attributes, then creating a single path of logic gave us just enough power to do what we needed to do while minimizing the amount of code required, and completely eliminated any boilerplate. However, this approach was not very configurable. By compiling these attributes into the code, we tightly coupled our application to the datasource. On this particular project it wasn't a big deal because it was a clients internal system and it fit the project timeline. However, on a "real product" implementing the logic with the Provider pattern or using something like the Castle Projects IoC would have allowed us the same power with a great deal more configurability. The downside of this is there is more to manage, and more that can go wrong with deployments, etc.