I am working with Laravel for almost two years and trying to understand all the benefits of using Repositories and DDD. I still struggle with how to use best practices for working with data and models for better code reusability and nicer Architecture.
I have seen other developers suggesting to generate models in factories and then use Repositories for saving these models like :
public function add(User $user)
{
return $user->save();
}
but what should I do, in case my user model has models related with it, like images, description and settings.
Should I create repository for each model and call ->add() function 4 times in the controller or should I place the saving logic inside the UserRepository ->add() function passing all models as well as user? Also, how about update function, that logic might also be quite complicated.
Update - what I need is a practical example with realization.
It's always difficult to deal with "right way" questions. But here is one way.
From a DDD perspective, in this specific context, treat the User object as an aggregate root entity and the other objects as child value objects.
$description = new UserDescripton('Some description');
$image1 = new UserImage('head_shot','headshot.jpg');
$image2 = new UserImage('full_body','fullbody.jpg');
$user = new User('The Name',$description,[$image1,$image2]);
$userRepository->persist($user);
First thing to note is that you if really want to try and apply some of the ddd concepts then it is important to think in terms of domain models without worrying about how to persist them. If you find that you are basically writing a CRUD app with a bunch of getters and setters and almost no business logic then pretty much forget about it. All you will end up doing is to add complexity without much value.
The persist line is where the user will get stored. And you certainly don't want to have to write a bunch of code to store and update the children. Likewise, it would normally be waste of effort to make repositories for value objects. If you are going this route then you really need some sort of database layer that understands individual objects as well as their relations. It is the relations that are the key.
I assume you are using Laravel's Eloquent active record persistence layer. I'm not familiar enough with it to know how easy it is to persist and update an aggregate root.
The code I showed is actually based more on Doctrine 2 Object Relation Mapper and pretty much works out of the box. http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/ It is easy enough to integrate it with Laravel.
But even Doctrine 2 is largely CRUD oriented. In different domain contexts, the user object will be treated differently. It can start to get a bit involved to basically have different user implementations for different contexts. So make sure that the payoff in the domain layer is worth the effort.
I am not a PHP guy but from what I can find, Laravel an MVC framework, which has nothing to do with DDD.
Check this presentation, it does not to go to domain modelling, more concentrating on tactics but at least it has some goodness like command handling and domain events, briefly explains repositories with active record.
It also has references to two iconic DDD books at the last slide, I suggest you have a look at those too.
I'm new to Backbone.js and in my recent project I need a custom validation mechanism for models. I see two ways I could do that.
Extending the Backbone.Model.prototype
_.extend(Backbone.Model.prototype, {
...
});
Creating custom model that inherit from Backbone model
MyApp.Model = Backbone.Model.extend({ ... });
I quite unsure which one is a good approach in this case. I'm aware that overriding prototype is not good for native objects but will that applies to backbone model prototype as well? What kind of problems I'll face if I go with the first approach?
You are supposed to use the second approach, that's the whole point of Backbone.Model.extend({}).
It already does your first approach + other near tricks to actually setup a proper inheritance chain (_.extend is only doing a copy of the object properties, you can look up the difference in code for Backbone's extend() and Underscore's _.extend, they are very large and not very interesting. Just extending the .prototype isn't enough for 'real' inheritance).
When I first read your question, I misunderstood and thought you were asking whether to extend from your own Model Class or directly extend from Backbone Extend. It's not your question, so I apologize for the first answer, and just to keep a summary here: you can use both approach. Most large websites I saw or worked on first extend from Backbone.Model to create a generic MyApp.Model (which is why I got confused, that's usually the name they give to it :)), which is meant to REPLACE the Backbone.Model. Then for each model (for instance User, Product, Comment, whatever..), they'll extend from this MyApp.Model and not from Backbone.Model. This way, they can modify some global Backbone behavior (for all their Models) without changing Backbone's code.
_.extend(Backbone.Model.prototype, {...mystuff...}) would add your property/ies to every Backbone.Model, and objects based on it. You might have meant to do the opposite, _.extend({...mystuff...}, Backbone.Model) which won't change Backbone itself.
If you look at the annotated Backbone source you'll see lines like
_.extend(Collection.prototype, Events, { ... Collection functions ...} )
This adds the Events object contents to every Collection, along with some other collection functions. Similarly, every Model has Events:
_.extend(Model.prototype, Events, { ... Model functions ...})
This seems to be a common pattern of making "classes" in Javascript:
function MyClass(args) {
//Do stuff
}
MyClass.prototype = {....}
It's even used in the Firefox source code.
I am looking for the simplest, best-practice approach to building a web app using EF database-first approach and the MVC 4.5/Web API. My application will use the angular framework to make ajax calls to retrieve json data on demand.
Currently, I'm getting excessive and ill-structured data in response to my api calls and would like to know how to go about cleaning that up.
The application will provide job tracking so I have tables like:
Person
Id
Name
Email
Department : FK -> Department
Department
Id
Name
Jobs
Id
RequestedBy : FK -> Person
AssignedTo : FK -> Person
JobHistory
Id
JobId : FK -> Jobs
So, ideally when I call
$http.get(/api/People)
I'd get:
[{Name: 'alice', Email: 'alice#here.com', Department: 'ABC'},
{Name: 'bob', Email: 'bob#here.com', Department: 'CDE'}]
I suppose this means that normally the principal entities will be eagerly loaded but not all the other tables with dependencies to Person. But there will be times when I want to use those back references to get all the jobs an individual may be working on or or has requested.
If possible, I'd rather not have to resort to things like modifying the T4 templates. While that is clever, it is not very flexible. Also, I dislike the idea of being given a power tool and told that I have to study the schematics and rewire the insides before using it. I'm not a professional developer and really want to focus on the job, not the tool; Linq2Sql was very good for that. Of course, if modifying the innards is the right answer, I'll take it.
This seems like such a straightforward use of the Web API I feel sure I'm missing something obvious.
Thanks
Edit
Additional info that is most likely causing part of my problem. At some point, to get the above to work, I added the following to Global.asax.cs:
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.All;
With eager loading, the two fields in Jobs that refer to Person result in a circular reference. The above code allows Json.Net to serialize it but fills the json with unwanted data. I believe the solution is to somehow switch to lazy loading but can this be done in the database first approach?
So, oddly enough, to get lazy loading to work with database first, I had to set the "Lazy Loading Enabled" to false in the properties of the ConceptualEntityModel.
I then added
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
in Application_Start() and removed the PreserveReferencesHandling as mentioned above in the question. That gave me the clean json I wanted from my model.
One difficulty still remains but barring a better response, I will work around it. In my PersonRepository I use:
public IEnumerable<Person> GetAll() {
return db.People
.Include("C_Departments")
.AsNoTracking();
}
To get the people along with their Departments. Unfortunately, if there is a navigation property in the Departments entity pointing back to people, it eagerly loads all members of the department along with the department info. In other words, at the .Include, lazy loading stops again.
Using Durandal, I have two view models within my app, let's say vmCompanies & vmEmployees. I have two views, one for each view model and within each, you can see all companies & all employees.
However, when I'm loading my employees, in the DB they have an ID for which company they are employed by. What I'd like to do is the following pseudo:
From within the vmEmployees, get a reference to the vmCompanies
If the vmCompanies has already been initialized (which I know it is 99% of the time), get a reference to it so I can use something like linq.js to find the specific company this employee works for
If the vmCompanies has not been initialized (aka: activated), do so
This way I can avoid the requirement of the vmEmployees having it's own internal cache of companies. So far I've been unable to figure out how in Durandal to query and ask "give me this view model that you've already loaded." It seems like it has that internally because when I navigate between views, they are cached and not reloaded (same with the VMs)... I've just so far been unable to see how I can do it.
You can manually require() a view model by its ____moduleId____. As long as your view model module returns an object and not a function, you'll be dealing with a singleton, so you can be sure you'll get the correct instance.
If you're not sure what the __moduleId__ is, you can use this chrome extension to view your view model's properties, including __moduleId__.
However, instead of manually instantianting VMs, a better alternative may be to create a separate module that you use to store the cached companies. I have a data module with its own internal cache that I use generically for this purpose, but you could create one specifically for companies, and store that information in it. It could even be responsible for loading its own data, if that's appropriate.
Here's some simple code to help explain:
Note this uses the sugar syntax for require JS - if you're using the array-based syntax, you'll need to translate accordingly. I can help if needed.
//companies-cache.js
define(function(require){
//some auto-loading logic here, if you wish
var companies = ko.observableArray([]);
return {
companies: companies
};
});
//vmCompanies, vmEmployees
define(function(require){
var companiesCache = require("viewModels/companies-cache");
//additional properties for this specific VM
...
return {
companies: companiesCache.companies
};
});
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
NOTE:
This question has been updated to provide more detail and insight than the previously.
UPDATE:
I just want to say thank you to everyone who responded. I'm still pretty much in the dark on what design pattern would work best for the Widget. Perhaps one of the Factory or Builder patterns?
I am just getting started on a new project and need to use MVC, OO and design patterns.
Here's the idea: Imagine a page that displays a set of widgets. These widgets are (usually) charts that are based off of data contained in several separate tables in the database. I use a running example of page that reports on a student's performance.
High Level Requirements
a page that displays a set of (HTML only) widgets.
widget's data will be based off a database query.
the page can be used to view separate datasets containing similarly laid out data. For example, a single page will display widgets that report on various aspects of a single student's performance.
want to see another student's performance, pull up another page. Displaying different widgets for different students is not needed (though it may be nice to have later).
There may be many students, but data contained in the database is similarly laid out for all students.
the way a widget is displayed may be changed easily (say changing a widget from displaying as a pie chart to display as a bar chart).
widgets should be able to be created quickly.
Low Level Requirements
Currently data does not change so widgets will not need to automatically update themselves.
Widgets may represent a ratio of two things (eg. a ratio of failed tests to successful tests as a pie chart), a series of points, or sometimes a single numeric value.
Development of new widgets should be a breeze, existing code need not be modified.
Framework to be used: Zend Framework, based on MVC.
There are (minimally) three things to define a widget: the dataset to report on (in the example above, the student ID), the query that describes the metric being reported, and a render mode (barchart, timeseries etc).
Here is a pass at breaking down the responsibilities of each layer of the MVC:
View: Zend views are HTML templates with PHP injected. They will contain one of several types of widgets. Widgets are of various forms including: static JPEG images (loaded from a remote site ie: <img src="http://widgetssite.com?x=2&y=3"/>, JSON based javascript widgets, or charts of various kinds (piechart, bar chart etc.)
Controller: Creates the widgets, assigns them to the view afterwards. The set of widgets that is to be displayed on a page needs to be maintained somewhere. Since I can't think of a good way to do this in the view, I'll add this to the controllers responsibilities for now. If there's a better place for this please shout. The controller will also have to handle any other input parameters and passing them to the widget. For example, the data_set id which may be passed at the url line as http:/.../report/?student_id=42
Model: The model, in the Zend Framework, is responsible for pulling the data and as such will most likely contain a class for each widget for accessing the database.
Some points:
The model here, represents the data for a particular widget. So necessarily, it will need to know what the query is going to be, in order to pull together the tables necessary to fetch that data.
There's an additional processing step that will most likely be necessary before the widget can present the data. This is dependant upon which renderer will be used. Sometimes it may require forming a url out of the data returned. Other times, a JSON array. Other times perhaps creating some markup. This can go either in the model or the controller or the view. Unless anyone can think of a good reason to move it to the controller or view, it is probably best to let this live in the model and keep the view and controller thin.
Likewise, a widget will be made up of 3 things, its parameters, its data, and its renderer.
One big part of the question is: What's a good way to represent the widget in an Object Oriented design? I already asked this once, couldn't get an answer. Is there a design pattern that can be applied to the Widgets that makes the most sense for this project?
Here's a first pass at a rather simple class for the Widget:
class Widget{
//method called by the view
render() {//output the markup based on the widget Type and interleaved the processed data}
//methods called by the controller:
public function __construct() {//recieve arguments for widget type (query and renderer), call create()}
public function create() {//tell the widget to build the query, execute it, and filter the data}
public function process_data() {//transform into JSON, an html entity etc}
//methods called by the model:
public function build_query() {...};
public function execute_query() {...};
public function filter_data() {...};
}
Looking at it, I can already see some problems.
For example, it is straightforward to pass the widget that was created in the controller to the View to render.
But when it comes to implementing the model it seems not so straight forward. Table Gateway Pattern is simpler to implement than ORM. But since table gateway pattern has one class for each model/table it doesn't seem to fit the bill. I could create a model for a particular table, and then within that, instantiate any other models needed. But that doesn't seem so to fit the Table Gateway Pattern, but rather ORM pattern. Can Table Gateway Pattern be implemented with multiple tables? What alternatives are there? Does it make sense that the controller creates the widget and the widget creates the Model?
Another issue that arises is that this design does not enable ease of widget creation. ie. Say I wanted to create a PiechartWidget, how much code can be reused? Would it not make more sense to use some OO ideas such as an interface or abstract classes/methods and inheritance?
Let's say I abstract the Widget class so only the shared methods are defined concretely, and the rest are declared as abstract methods. Revising the Widget class to make it abstract (second pass):
abstract class Widget{
private $_type;
private $_renderer;
//methods called by the controller:
//receive arguments for widget type (query and renderer),
protected function __construct($type, $renderer) {
$this->_type = $type;
$this->_render = $renderer;
$this->create();
}
//tell the widget to build the query, execute it, and filter the data
private function create() {
$this->build_query();
$this->execute_query();
$this->filter_data();
}
//methods called by the model:
abstract protected function build_query();
protected function execute_query() {
//common method
}
abstract protected function filter_data();
//method called by controller to tranform data for view
//transform into JSON, an html entity etc
abstract protected function process_data();
//method called by the view
//output the markup based on the widget Type and interleave the processed data
abstract protected function render();
}
Is this a good design? How could it be improved?
I assume writing a new widget will require at least some new code to build the query, and maybe filter the data, but it should be able to use preexisting code for almost all of the rest of its functionality, including the renderers that already exist.
I am hoping anyone could provide at least some feedback on this design. Validate it?
Tear it apart. Call me an idiot. That's fine too. I could use any forward traction.
A few specific questions:
Q1. What's the best way to implement the renderers, as part of the Widget class or as a separate class? 1a. If separate, how would it interact with the widget class(es)?
Q2. How could I improve this design to simplify creation of new kinds of widgets?
Q3. And lastly, I feel like I am missing something here with regards to data encapsulation. How does data encapsulation relate to the requirements and play out in this scenario?
For #2, if you are using WPF on windows, or Silverlight in general, consider using MVVM pattern (Model-View-ViewModel), here is explanation with a WPF implementation:
MVVM at msdn
For #1 (comments not answer): For exact implementations (and minor variations) of MVC, it really depends on what language you are using.
Another alternative to MVC is MVP Model View Presenter
Remember the goal of OO is not to cram design patterns into your code, but to create maintainable code with less bugs/increased readability.
High Requirements
- a page that displays a set of widgets. widgets are based off of data contained in several separate tables in the database.
- widget's data will be based off a database query. widget display its data in a particular way.
- widgets should be able to be created quickly.
Low Level Requirements
- Data changes, multiple charts need to change, push model (from data to ui)
- Development of new widgets should be a breeze, existing code need not be modified
Advice from design patterns basics
- MVC supports one to many notification pattern, so yes, once your widget is initialized, created and connected to the web page, it should wait for notifications from the database.
- Strategy pattern, your entire code should develop to a interface. New widgets should be added to a parametrized LinkedList (or some other data structure). That way new widget developers just implement the interface and your framework picks up these notifications without change to existing code.
Siddharth
The purpose behind all of these ideas -- MVC, patterns, etc. -- is essentially the same: every class should do one thing, and every distinct responsibility in your application should be separated into distinct layers. Your views (page and widgets) should be thin and make few if any decisions other than to present data gathered from the models. The models should operate on a data layer agnostically, which is to say they should not know whether the source of their data is a specific kind of data source. The controllers should be thin as well, acting basically as a routing layer between the views and models. Controllers take input from the users and perform the relevant actions on the models. The application of this concept varies depending on your target environment -- web, rich client, etc.
The architecture of the model alone is no trivial problem. You have many patterns to choose from and many frameworks, and choosing the right one -- pattern or framework -- will depend entirely on the particulars of your domain, which we have far too few of here to give you more specific advice. Suffice it to say it is recommended you spend some time getting to know a few Object-Relational Mapping frameworks for your particular technology stack (be it Java, .NET, etc.) and the respective patterns they were built on.
Also make yourself familiar with the difference between MVP and MVC -- Martin Fowler's work is essential here.
As for design patterns, the application of most of the standard GOF patterns could easily come into play in some form or another, and it is recommended you spend time in Design Patterns or one of the many introductory texts on the subject. No one here can give specific answers as to how MVC applies to your domain -- that can only be answered by experienced engineers in cooperation with a Product Owner who has the authority to make workflow and UI decisions that will greatly affect such decisions in their particulars.
In short, the very nature of your question suggests you are in need of an experienced OOP architect or senior developer who has done this before. Alternatively give yourself a good deal of time in intensive study before moving forward. The scope of your project encompasses a vast amount of learning that many coders take years to fully grasp. This is not to say your project is doomed -- in fact you may be able to accomplish quite a lot if you choose the right technology stack, framework, etc., and assuming you are reasonably bright and focused on the task at hand. But getting concepts as broad as "MVC" or "OO" right is not something I think can be done on a first try and under time constraints.
EDIT: I just caught your edit re: Zend. Having a framework in place is good, that takes care of a lot of architectural decisions. I'm not familiar with Zend, but I would stick to its defaults. Much more depends here on your ultimate UI delivery -- are you in a RIA environment like Flash or Silverlight, or are you in a strict HTML/JavaScript environment? In either case the controllers should still be thin and operate as routers taking user requests from HTTP gets and posts, and immediately handing off to the models. The views should remain thin as well and make as few decisions as possible. The concept of MVC applied in a web environment has been pretty well established by Rails and the frameworks that followed, and I'm assuming Zend is similar to something like CakePHP in this regard: the application server has a routing system that maps HTTP calls to controller actions that respond with specific views. The request/response cycle is basically this:
User request posted through a URL
Router hands control to a controller class
Controller makes a call to a model with the given params
The model operates on the data, posts back to the controller
The framework maps the finished data into a view, with some kind of code-behind that puts the results of the request in the view's scope.
The framework creates html (or xml or whatever) and posts back to the caller.
It sounds like you want to use MVC and other patterns because they are the new buzz words. Splitting your design among model view and controller should tell you how to spread the functionality of your application. Although I totally agree that using MVC is the correct approach, I suggest you research the pattern and look at some source code that implements it. As a start to your question though, the widgets that will be displayed will be your views, that much should be obvious. Input from the user, such as changing a parameter of some widget or requesting other information will come into your application and should be handled by a controller. A concrete example of this is a Java-based HttpServlet. The controller servlet receives the user request and asks the lower layers of your app (Service, Persistence, etc) for an updated representation of your model. The model includes all of your domain-specific objects (i.e the data from your databases, etc). This data (the updated model) comes back to the controller, which in turn pushes out a new view for the user. Hopefully that is enough to get you started about designing your app.
As further help, you could consider using a framework to assist in the development of your app. I like Spring a lot, and it has a first class MVC implementation that really helps guide you to designing a correct MVC web app.
You may consider using Subject Observer Pattern
Have your class, named DataReader as single Subject. Your multiple widgets will act as Observers. Once your DataReader receives data from server, it (Subject) will inform multiple widgets (Observer).
Your individual widgets may have different presentation to present to same set of data from DataReader.
Update
In the message where subject notify observer, you may include the message type information as well. Widgets will only process message type, which is within their own interest, and ignore rest of the message.
NOTE: This is my new answer based on new the updated question.
Here is a proposed class diagram. I'm going to work on a sequence diagram.
My old answer is here:
Based on the requirements you describe, your model is your database or data warehouse and your views are your pie charts, bar graphs, etc. I don't see the need for a controller, because it sounds like you have a one page dashboard with widgets.
You need to spend your time on the database model. Since you're doing all selects and no updates, go for a de-normalized data model that makes these queries efficient. You should put the results of these queries in a table type object (e.g. 2-dimensional array) or 3-dimensional array based on the amount of dimensions. You are limited to 3 dimensions unless you use animation.