Could someone point me to a definition of "hydrate" and "dehydrate" as it applies to Livewire components? The only hit in the documentation search refers to
Livewire will take care of hydrating and dehydrating the model between requests with the current, non-persisted data.
In the Lifecycle hooks section, the hydrate and dehydrate class hooks are self referential.
hydrate: Runs on every request after the component is hydrated...
Responses to similar questions have indicated that hydration is filling a object with data after it's been instantiated -- that kinda makes sense, but what would "dehydrating" an object would be?
I don't know if there is a good definition of the lifecycle in the documentation other than the hooks.
I'll explain my understanding of it.
So there are two levels of hydration essentially in Livewire, one is hydrating a component, and the other is hydrating the properties of a component.
Livewire needs to send data back and forth between php and javascript for it to work the way it does. As part of the messages that get sent there is information about the component, and information about the properties. But for the information to be accessible and usable by javascript it needs to be in the right format.
The process of hydration is taking the message and converting its values back into php, creating the Livewire component and creating any of the properties that component has.
Dehydration is the reverse, it goes through all the properties, and serialises them, then it serialises the component and bundles that all into a message that gets sent to the front end.
Caleb has addressed this very question in a blog entry. The post linked to below is also linked to from the Livewire Docs, though I admit that it is only linked to from a lowly sub-section of the documentation.
I really do think that information like this should be put front-and-centre to lay the groundwork for other people's understanding the framework. Documentation that requires additional foot-notes to gain a full understanding, is by definition, not Documentation, right!?! Anyway, point is, I don't blame anyone for missing it!
Blogpost found here >>
The official explanation isn't actually much different from the answer already accepted (#JoshHanley). Nevertheless, I do find the blog to be clearer and better explained, and might help others in future.
I know that (according to SO guidelines) I'm supposed to re-word the answer as well as link to a resource, but honestly there's no short way of explaining a framework like this. You just gotta jump into the deep end I'm afraid.
Related
Can someone please clarify the following topic? I haven't found enough complex answer to this, just some basic examples of how this should work, so I am asking here.
Let's say we have an entity Invoice. The Invoice has some private props like date issued, payment date, Items, etc.
By the principle of DDD the Domain should care only about itself and never about the world around. In case of Invoice it means, you can issue it, you can add item, you can probably change the payment date etc.
But is responsibility of the Invoice to care about extracting data from it? I mean, e.g. in Doctrine you would create getters for all of the properties and it would be definitely fine. But I believe this is not something you want to do in DDD - I think the Invoice should care only about it's state and modifying it and not about providing hundreds of getters for all of its properties.
So my question is - what is the best way, to extract data from Entity to e.g. DTO? Is it really getters? Or should you use maybe the reflection? Entity => Transformer (using Reflection) => DTO?
By the way, when you are converting Entity to DTO, should you use the third, transformer, class, or invoke some method on Entity to convert itself into the DTO (like $Invoice->toDetailDto())? I think that calling ->toDetailDto is violation of Single responsibility, but on the other side, it solves the problem with accessing private properties of Entity without using Reflection and without hundreds of getters.
Can someone please clarify the following topic?
This is not your fault -- the literature sucks.
By the principle of DDD the Domain should care only about itself and never about the world around
Yeah, about that... it's kind of a lie. Pouring information into an object is pointless unless there is some way of getting the information back out. (Analogy: /dev/null is an awesome database if you don't need to get information back out of it again.)
"How do I get information out of you?" is part of the contract of the object; that part of the contract might be questions that you ask the object to get information, or it might be that the object sends information "somewhere else", and you can look there.
For example, the cargo shipping demonstration, the Cargo "aggregate root" includes a number of methods for copying information out of the object.
For something like a DTO, part of the riddle is figuring out whether the domain model interface should include a dependency on the DTO definition. Most commonly, the answer is no: dependencies normally point toward the domain model, rather than away from it. But "no" isn't the only possible answer; if the DTO definition is stable (because, for example, it is defined by some industry standard), then you aren't any more likely to run into problems there than you are with using Strings or numbers.
Reflection... it can be the right choice. If nothing changes, or if everything always changes in lock step, then reflection is fine. When you need to change the implementation of the domain model and keep the definition of the DTO stable so that you don't break clients, it may get messier, depending on how many different places in the code apply reflection to the domain model, and whether or not you can find them all when the time comes.
I need help with something I can’t get my head wrapped around regarding the Repository and Service/Use-case pattern (part of DDD design) I want to implement in my next (Laravel PHP) project.
All seems clear. Just one part of DDD that is confusing is the data structures from repositories. People seem to choose data structures the Repository should return (arrays or entities) but it all has disadvantages. One of which is performance looking at my experiences in the past. And one is which you don’t have interfaces for simple data structures (array or simple object attributes).
I’ll start with explaining the experience I have with a previous project. This project had flaws but some good strengths I learned from and like to see in my new project but with solving some design mistakes.
Previous experience
In the past I’ve build a website that was API Centric using the Kohana framework and Doctrine 2 ORM (data mapper pattern). The flow looked like this:
Website controller → API client (HMVC calls) → API controller → Custom Repository → Doctrine 2 ORM native Repository/Entity-manager
My custom Repository returned plain arrays using Doctrine2 DQL. Doctrine2 recommends array result data for read only operations. And yes, it made my site nice and light. The API controller just converted the array data to JSON. Simple as that.
In the past my company created projects relying fully on loaded Doctrine2 entities and it’s something we regretted due to performance.
My REST API supported queries like
/api/users?include_latest_adverts=2&include_location=true
on the users resource. The API controller passed include_location to the repository which directly included the location relation. The controller read latest_adverts=2 and called the adverts repository to get the latest 2 adverts of each user. Arrays were returned.
For example first user array:
[
name
avatar
adverts [
advert 1 [
name
price
]
advert 2 [
….
]
]
]
This proved to be very successful. My whole website was using the API. It would be very easy to to add a new client because the API was perfectly in production already using oauth. The whole website runs on it.
But this design had flaws too. My controller still contained A LOT of logic for validation, mailing, params or filters like has_adverts=true to get users with adverts only. It would mean that if I created a new port, like a total new CLI interface, I would have to duplicate alot of these controllers due to all the validation etc. But no duplication if I would create a new client. So at least one problem was solved :-)
My admin panels were completely coupled to the doctrine2 repository/entity-manager to speed up development (sort of). Why? Because my API had fat controllers with special functionality for the website only (special validation, mailing for registering etc). I would have to redo work or refactor a lot. So decided to use the Entities directly to still have some sort clear way of writing code instead of rewriting all my API controllers and move them to Services (for site & admin) for instance. Time was an issue in fixing my design mistakes.
For my next project I want all code to go through my own custom repositories and services. One flow for good separation.
New project (using DDD ideas) and dilemma with data structures
While I like the idea of being API centric, I don’t want my next project to be API centric in core because I think the same functionality should be available without the HTTP protocol in between. I want to design the core using DDD ideas.
But I liked the idea using a layer that just talked as a API and returns simple arrays. The perfect base for any new port, including my own frontend. My idea is to consider my Service classes as the API interface (return the array data), do the validation etc. I could have Services specially for the website (registering) and plain services used by the Admin or background processes. In some admin cases a Service would not be required anyway for simple CRUD editing, I could just use Repositories directly. Controllers would be very thin. With this creating a real REST API would just be a matter to create new controllers using the same Services my frontend controller classes do.
For internal logic like business rules it would be useful to have Entities (clear interfaces) instead of arrays from repositories. This way I could benefit from defining some methods that did some logic based on attributes. BUT If I would be using Doctrine2 and my repositories would always return Entities my application would suffer a big performance hit!!
One data structure ensures performance but no clear interfaces, the other ensures clear interfaces but bad performance when using a Data Pattern pattern like Doctrine 2 (now or in the future). Also I could end up with two data types which would be confusing.
I was thinking something similar to this flow:
Controller (thin) → UserService (incl. validation) → UserRepository (just storage) → Eloquent ORM
Why Eloquent instead of Doctrine2? Because I want to stick a bit to what’s common within the Laravel framework and community. So I could benefit from third party modules, for example to generate admin interfaces or similar based on models (bypassing my DDD rules). Other than using third party modules, I would design my core stuff so switching should always be easy and not affect data structure choices or performance.
Eloquent is an activerecord pattern. So I would be tempted to convert this data to POPO’s like Doctrine2 entities are. But nope... as said above, with doctrine2 real models would make the system very fat. So I fall back to simple arrays again. Knowing this would work for both and any other implementation in the future.
But it feels bad always rely on arrays. Especially when creating internal business rules. A developer would have to guess values on arrays, have no autocompletion in his IDE, could not have special methods like in Entity classes. But making two ways of dealing with data feels bad too. Or I am just too perfectionist ;) I want ONE clear data structure for all!
Building interfaces and POPO’s would mean a lot of duplicate work. I would need to convert an Eloquent model (just a table mapper, not entity) to an entity object implementing this interface. All is extra work. And eventually my last layer would be just like a API, thus converting it to arrays again. Which is extra work too. Arrays seem the deal again.
It seemed so easy reading up into DDD and Hexagonal. It seems so logic! But in reality I struggle with this one simple issue trying to stick to OOP principles. I want to use arrays because it’s the only way to be 100% sure I am not depended on any model choice and querying choice from my ORM regarding performance etc and don't have duplicate work in converting to arrays for views or an API. But there's no clear contract on how a user array could look. I want to speed up my project using these patterns, not slow them down :-) So not an option to have many converters.
Now I read a lot of topics. One makes POPO’s & interfaces that conform proper entities like Doctrine2 could return, but with all the extra work for Eloquent. Switching to Doctrine2 should be fairly easy, but would impact performance so bad or one would need to convert Doctrine2 array data to these own entity interfaces. Others choose to return simple arrays.
One convinces people to use Doctrine2 instead of Eloquent, but they leave out the fact that Doctrine2 is heavy and you really need to use array results for read only operations.
We design repositories to be changeable right? Not because it’s “nice” by design only. So how could we rely on full Entities if it has such big impact on performance or duplicate work? Even when using Doctrine2 only (coupled) this same issue would arise due to its performance!
All ORM implementations would be able to return arrays, thus no duplicate work there. Good performance. But we miss clear contracts. And we don’t have interfaces for arrays or class attributes (as a workaround)... Ugh ;)
Do I just miss a missing block in our programming languages? Interfaces on simple data structures??
Is it wise to make all arrays and have advanced business logic talk to these arrays? Thus no classes with clear interfaces. Any precalculated data (normally would be returned by an Entity method) would be within an array key defined the Service class. if not wise, what’s the alternative considering all of the above?
I would really appreciate if someone with great experience in this “domain” considering performance, different ORM implementations, etc could tell me how he/she has dealt with this?
Thanks in advance!
I think what you are dealing with is something similiar I'm struggling with. The solution I'm thinking works best is:
Entities/Repositories
Use and pass around Entities always when performing Write operations (Creating things, Updating things, Deleting things, and complex combinations thereof).
Sometimes you may use Entities when doing Read operations (when you anticipate the Read might need to be used for a Write soon after...ie. ->findById is soon followed by ->save).
Anytime you are working with an Entity (whether it be Write or Read), the Repositories need to be the place to go. You should be able to tell new developers that they can only persist to the database through Entities and the Repository.
The Entities will have properties that represent some Domain Object (many times they represent a database table with the fields of a table, but not always). They will also contain the domain logic/rules with them (ie. validation, calculations) so they are not anemic. You may additionally have some domain services if your Entities need help interacting with other Entities (need to trigger other events), or you just need an additional place to handle some extra domain logic (perform Repository calls to check for some unique conditions).
Your Repositories will solely be for working with Entities. The Repositories could accept Entities and do some persistence work with them. Or they could accept just some parameters, and do some reading/fetching into full Entities.
Some Repositories will know how to save some Domain Objects that are more complex than others. Perhaps an Entity that has a property which contains a list of other Entities that need to be saved along side the main entity (you can dive deeper into learning about Aggregate roots if you want).
The interfaces to Repositories rest in your Domain layer, but not the actual implementations of those Repositories. That way you can have an Eloquent version or whatever.
Other Queries (Table Data Gateway)
These queries won't work with Entities. They'll just be accepting parameters and returning things like Arrays or POPO's (Plain Old PHP Objects).
Many times you will need to perform Reads that do not return nicely into a single Entity. These Reads are typically more for reporting (not for CRUD-like operations, like Reading a user into an edit form that is eventually submitted and saved). For example, you might have a report that is 200 rows of JOINed data. If you used the Repositiory and tried to return large deep objects (with all the relationships populated, or even lazy-loaded) then you are going to have performance issues. Instead, use the Table Data Gatway pattern. You are just displaying data and not really needing OOP power here. The outputted data could however contain ID's, which through the UI could be used to initiate calls to Repository persistence methods.
As you are developing your app, when you come across the need for a new Read/Report query, create a new method in some class somewhere in your Table Data Gatway folder. You may find you have already created a similar query, so see how you can consolidate the other query. Use some parameters if necessary to make the gateway method's queries more flexible in particular ways (ie. columns to select, sort order, pagination, etc.). Don't make your queries too flexible though, this is where query builders/ORMs go wrong! You need to constrain your queries to a certain extent to where if you need to replace them (perhaps a different database engine) then you can easily perceive what the allowed variations are and aren't. It's up to you to find the right balance between flexibility (so you have more DRY code) and constraints (so you can optimize/replace queries later).
You can create services in your Domain to handle receiving parameters, then passing them to the Table Data Gateway, and then receiving back arrays to do some more mutating on. This will keep your Domain logic in the domain (and out of the infrastructure/persistence layer of the Repository & Table Data Gateway).
Again, just like the Repository, use interfaces in your domain services so that the implementation details stay out of your Domain layer, and resides in the actual Table Data Gateway folder.
I have been trying to figure out if the request object should handle sorting out the controller and action or if that should be left up to the router? What I mean is that when the request object is passed to the router, if it should already contain the properties for the controller and action. Forgive me if this has been answered before but I couldn't find anything specific to this topic.
Most of the content I have found on this doesn't even use a request object. I know I could download a framework and look but I figure it might be just as easy to ask here.
This is very different in many Frameworks, but the basics are similar to this:
The Request Object (or any other kind of container for the passed input data) should only have this one responsibility: Containing the input (and sometimes result) data.
A specific other object (Called "Front Controller" in many frameworks) should sort out what controller and action to be called and nothing else.
This logic usually continues with the actuall called controller that only has the responsibility of selecting the correct model, and the model of only handling the data. Some frameworks split this even further.
But the theory is allways same: Each part of your app should only have to focus on one single task.
The link from #teresko above tells you the theory behind this: http://en.wikipedia.org/wiki/Single_responsibility_principle
I'm a big enthusiast about new Zend Framework. I had done one project in the previous version so far and I decided to learn new one which contains a really hard parts to understand for me.
I've watched webinars and youtube videos, also I read the documentation and I'm trying to understand this framework simply by read the code but there are few things I just can't figure out.
There is a lot information about EventManager in webinars but since I'm lack at English I'm just not able to understand 100% of the speech.
I know that event manager manage events which is quite obvious but I don't really know how to use it: in one of the webinars they provide some simple examples but they don't explain where to put this code, is it module.php file? Or some other place if you can show me some practical example with explanation so i can see whats the point.
Next thing is that mysterious $e passed as an argument to most of the functions in Module.php which after is used like this: $e->getApplication or something I just wonder what this $e stands for? It is instance of what? And next thing is how it is passed "automatically" to these functions?
Another problem: in configuration files which are specified for each module called module.config.php there is a lot of things. I got the point of routes I've understood them but I can't figure out what are the invokables and factories. It is also explained in one of the webinars as follow: invokables are paths to classes, factories are callable functions or classes (cant remember). The point is OK, that make sense in some theoretical talk but please provide me some examples with in depth explanation, where those factories and invokables come from and other stuff that I need to know.
The other thing is that there is a lot of configuration possibilities in those configuration files. Where can I find some informations about what "keys"=>"values" are possible in those files?
That's all for now but there are still unanswered questions i would like to ask. If someone is able to help me, I would really appreciate to correspond via mail with this person.
Ok one problem is solved. The one about mysterious &e so if somene is intersted in here is a solution:
This $e variable instance depends on what function we use in module.php file:
case 1: init() -> &e is an instance of module manager
case 2: onBootstrap() -> &e is an instance of MvcEvent
(if there are other cases i havent found please let us know)
The thing is that those methods are called when event has been triggered so mysterious &e is passed to those functions by listenerers which are listening if these functions appears in our code (this is my simple logic of that so please dont hate me)
There are still other questions to answer.. as soon as ill figure out some senseful answer i will let you know
Within stock ZF2 code, $e is always an instance of Zend\EventManager\EventManagerInterface. Usually it is either an Zend\EventManager\Event or an Zend\Mvc\MvcEvent.
A class' EventManager triggers an event which results in listener callbacks being called. Each listener callback is passed an instance of an Event which then has some useful methods, notably getTarget() and getParams(). Other instances of EventManagerInterface usually have more specialised methods. MvcEvent in particular has methods related to the Mvc component, such as getApplication(), getRouter(), getRequest() and getResponse().
You can find more information about tghe EventManager, application configuration and MvcEvent in the "Using Zend Framework 2" book: http://leanpub.com/using-zend-framework-2
I have a doubt with the implementation of the model and can not find a reasonable explanation for the problem.
I'll give you an example I'm working, it is an MVC implementing a blog.
I am ControllerPost which is responsible for control of reading a particular post Blog
consequently have the ModelPost
the ModelPost must contain all methods needed?
method getPost()
method getComment()
method getArchive()
or should I isolate the methods?
ModelPost
method getPost()
ModelComment
method getComment()
ModelArchive
method getArchive()
this causes me much confusion, I see examples but no proper explanation.
I hope that was clear in my doubts, otherwise try to be more explanatory
Thank all
In most projects I've worked on, we've had a model class for a database table.
Using mostly Zend MVC, that would mean extending the Zend_Db_Table classes for each entity.
So in your case, if the comment, post and archive are different tables (which I suppose they are), I'd build separate classes with get, update, insert and delete (and other similar) methods.
This might steer a bit off topic, but I suggest you look into domain driven development (DDD):
There are links to some good reading material here: Domain-driven design with Zend
Also give this a read:
http://phpmaster.com/building-a-domain-model/
http://phpmaster.com/integrating-the-data-mappers/
http://phpmaster.com/an-introduction-to-services/
The main thing about the DDD is that it switches your mindset from thinking about database tables, more towards thinking about the main logical parts of your application, and then slowly adding a persistence layer below it and the application and service layers above it.