[NFR] Phalcon\Forms\Form::setDefaults()
Method setDefaults would populate form with data. It would not require to pass $entity as bind() does.
Syntax
public Phalcon\Forms\Form setDefaults (array $data)
Binds $data to corresponding form elements.
Usage example
$values = array(
'field1' => `value1`,
'field2' => `value2`,
);
$form->setDefaults($values);
Why not to use bind method?
Because often form elements don't map model fields. Let's say one order form is used to populate two models: addresses and customers. You can't use existing bind method because you don't have appropriate model entity.
Implementation
I have already extended Phalcon's form class by adding the method below. It traverses all form elements and set default value on each element. Of course if the value is provided.
public function setDefaults($values = array()) {
if(!count($values)){
return;
}
$elements = $this->getElements();
foreach($elements as $i => $element) {
$name = $element->getName();
if(isset($values[$name])){
$element->setDefault($values[$name]);
}
}
}
What's your opinion?
Please comment the idea! ;)
Want to back this issue? Post a bounty on it! We accept bounties via Bountysource.
How about Phalcon\Tag::setDefaults()?
//Assigning "peter" to "name" component
Phalcon\Tag::setDefaults(array("name" => "peter"));
//Later in the view
echo Phalcon\Tag::textField("name"); //Will have the value "peter" by default
@mruz I was unaware of such functionality. Thanks!
(1) However Phalcon\Tag::setDefaults() will not work if there are several (similar or identical) forms on one page and each form has the same field names. Am I correct?
(2) What is more, I think the situation when my suggestion might be helpful is where you have one form that is supplied from more than one model e.g.:
Form fields: name, surname, city, phone, email
So I want to be able to feed this form with data but my data are stored in two different arrays (from two different models).
$data1 = array(
'name' => 'Ahmad',
'surname' => 'Insh',
);
$data2 = array(
'city' => 'Damascus',
'phone' => '+111333',
'email' => '[email protected]',
);
$form->setDefaults($data1);
$form->setDefaults($data2);
@Conradaek I totally understand the problem you highlighted but I think the bind method is still perfect, hell even more useful, for this use case. What I think is lacking though is good documentation on how to tackle this issue.
First, in my opinion, the terms entity and model are often wrongly used interchangeably. To me, a model enforces business rules whilst an entity enforces how the business interacts with their data store. A model, therefore, "has an" entity (i.e. use composition not inheritance). With these distinctions in mind, here is how I design the M part in my MVC applications...
All my models go into the Model namespace whilst my entities go into the Model\Entity namespace. The entities are actually the ones that inherit from Phalcon\Mvc\Model. In fact, I actually think it is a misnomer (and unfortunately a common one) to call that base class Model so I alias Phalcon\Mvc\Model to Model\Entity which I then inherit from. I think the guys at Microsoft were right to call their ORM Entity Framework. ORMs basically deal with entities, not the model per se.
Here is how I create my entities:
- For each table in the database, create a corresponding entity.
- For each view in the database, create a corresponding entity.
The second step is actually what solves this issue nicely. Your form must map to or to a part of a view. A form is just a frontend interface to your data store.
Now, many developers just implement the first step which is what brings this issue about. Implementing a method like setDefaults does indeed help you fill that damn form but you might end up breaking the Don't Repeat Yourself principle.
There is a caveat with the second step which, I think, is one of the reasons why most developers don't use views. To make complex views updateable, you have to create triggers (or routines). This is not an issue if you know your DBMS well or you have a DBA available to you. However, that's not the only option. Phalcon is very powerful. You can use it's database events to create subentities in runtime until you have saved them all then stop it from trying to save to the view. Another easier option would be to pass the bind method an instance of a model and have the model handle saving the entities.
What I like about this design is that you end up with:
- very slim controllers,
- not so fat models whose only purpose is to make sure that all business requirements are met,
- and entities that only handle data storage and validation.
Your controllers should only interact with your models (not entities). This way you ensure that data only reaches your data store if it meets all business requirements. If you find yourself initialising transactions from within a controller you need to rethink your design.
@rushmorem Thanks a lot for your comment, it's very, very interesting.
Could you please provide any links to some useful materials to get me deeper to the concept? I mean some articles, blog posts, books? Or even phrases to look for in google?
If you find yourself initialising transactions from within a controller you need to rethink your design.
What do you mean? Is that mean that initialising transactions within controller is wrong so that I need to rethink my design in order to eliminate this? Or, is that mean that initialising transactions within controllers is acceptable but you need to be carefull about your design?
@rushmorem Am I right, it is about Domain Driven Development?
@Conradaek Over the years I have read so many books and watched so many videos on Design Patterns and Object Oriented-Design among others. Some that come to mind are:
- Design Patterns: Elements of Reusable Object-Oriented Software by the Gang of Four,
- Head First Design Patterns, and
- Simon Allardice's Foundations of Programming: Object-Oriented Design.
I would love to get some time to read up on Domain Driven Development but so far I haven't had enough time to do so. So whilst this design may or may not follow that programming paradigm, it's something that draws from my own experience and influenced by material around design patterns and object oriented-design techniques.
A quick way to get started is to google solid programming practices. Understanding SOLID principles is a must when building easy to maintain, reusable software. Utilising design patterns will help you achieve them without thinking about it too much. That's the point of design patterns... Some people have already thought about that problem so you don't have to reinvent the wheel.
As for transactions, putting them in the controller is wrong and you should avoid it. Your controllers should not know which data store you use. Down the line, say you want to switch from a relational database system to a NoSQL product (for example) you will have to edit your models AND controllers. You know what, you might not even need to be switching database systems. You could simply have restructured your database.
So where do you put them? Putting them in your model would be tempting as it's a lot easier and a lot less work when you are coding for the first time. In a way I was implying this when I said
Another easier option would be to pass the bind method an instance of a model and have the model handle saving the entities.
But this is not my preferred approach, and I honestly don't like it either. If you put it in the model classes then those models will have an additional responsibility. So again if you change your data store, you will have to update your models. A better method?
You can use it's database events to create subentities in runtime until you have saved them all then stop it from trying to save to the view.
and even better...
To make complex views updateable, you have to create triggers (or routines).
This means that you will just treat your view like a normal table (i.e. you can create, update and delete records as well). So your 'view' entity will just look like your normal entities. No additional code or transactions. You can then handle the saving logic in the database. This allows you to write cleaner and less code.
- No more transactions anywhere in your code. You will have moved them to your database. Even if you don't have a DBA available, I really think that every developer who uses relational databases ought to know
SQLanyway. Once you get used, it'sdeclarativenature will start sounding natural and you will wish you could program more like that :-) - No more coding Relationships between Models. Since you are now using views like normal tables, you just need to use the corresponding entity whenever necessary. I highly recommend you always enforce referential integrity at database level anyway. This is one of the huge advantages of relational databases. Since you are already using it, why not use it to your advantage?
- No more Aliasing Relationships.
- No more coding Virtual Foreign Keys.
- No more coding Cascade/Restrict actions.
This will help you:
- write less and easier code in your entities which leads to less bugs and improves maintainability,
- write faster software. You won't even need
lazy loadinganymore. When you need to pull data from different tables, just use a view entity and pull it all at once. Same applies to inserting, updating and deleting. You can make selects even faster by using materialised views if your relational DBMS supports them. - if you are fortunate enough that you do, have a DBA available then your team will even ship code faster because that duty will be delegated to the DBA whilst you program the entities.
- if you ever, happen to switch your programming language, you won't need to implement the logic for handling transactions and working with multiple tables as well since that logic is in your database. As a result, the transition will be faster.
Now, many programmers will tell you that the answer is always 'it depends'. What they mean is, these are good programming principles to follow but sometimes you are not trying to write easy to maintain or reusable software. Maybe you just want to hack a quick experiment together that you will soon discard, or writing a quick proof of concept etc. You will also hear that 'writing software is easy, but writing reusable software is hard'. I have problems with these statements.
- Always using good practices whenever you open your text editor to code will help these practices become second nature to you. Once it's ingrained, you won't have to think about them again on your next big project. You will ship better (more robust, reusable and easy to maintain) software faster.
- Many a time, quick experiments end up in production. You write a quick proof of concept. You have such a huge positive feedback and your clients need it like yesterday. You don't have time to write from scratch so you just tweak the prototype, push it to production then start working on a complete rewrite. Does this sound familiar? Instead of utilising that time to ship more features and quickly adapt to customer feedback, you are giving your competitors a grace period to catch up once they see your idea's potential.
- After all, how much more time will it take to write it properly in the first place? Whatever little time that is, you will make up for it in a huge way when you reap the benefits and avoid problems 1 and 2.
- That mentality spoils the ecosystem. Usually when, these programmers are demonstrating something they choose to ignore the principles because, well, it's just a quick tutorial! The end result is their students pick up on those bad practices and think it's the way it's supposed to be done. Once they get used to those bad practices, unlearning them will be a chore.
- If you think following
SOLIDprinciples to write reusable, easy to maintain software is harder, wait till your classes become fatter and fatter and you discover your code has bugs. Good luck debugging them. I certainly don't want to be in your shoes! This is when you will realise that the easier to maintain part doesn't always mean some months later after you have shipped your software. You will start reaping these benefits when you are still writing your software. Also, if you are followingBDDorTDDyou are also a lot less likely to break things during refactoring. And if you do, debugging and fixing will be a piece of cake and a lot faster.
@rushmorem
Sorry that I am answering to your message after 9 days but I simply didn't know what to answer... :)
I would like truly thank you for your awesome input. It is kind of inspiration for me and I am sure I will go deep the issues you have drew here! ;)
I am working on a project that is gonna be quite complex. I am not very experienced developer (less than two years) but I am still learning a lot.
Again, thanks a lot!!
@Conradaek
No problem. Glad I could be of some help to you :)
Thank you for contributing to this issue. As it has been 90 days since the last activity, we are automatically closing the issue. This is often because the request was already solved in some way and it just wasn't updated or it's no longer applicable. If that's not the case, please feel free to either reopen this issue or open a new one. We will be more than happy to look at it again! You can read more here: https://blog.phalconphp.com/post/github-closing-old-issues