I'm new at MVC and my first framework is Laravel (3 for now). I've started coding exclusively in the routes, and I moved to the controller. I'm however doing all of my database operations in the controller. I do not understand how to use the model.
Examples either demonstrate everything in the controller or in the route, but they never split the model, controller and view.
Could anyone kindly explain me how to use the model? In short I don't understand how to link one to each other, like sending form input to them model, or processed data back to the controller.
A github repo of a Laravel (v3 if possible) with a full MVC setup would be nice to analyze too, if anyone has one up for me to look at?
Thanks.
The best statement on the subject of Frameworks I've heard is due to Uncle Bob:
A good Architecture allows major decisions to be deferred!
Specifically:
A good Architecture delays choosing a Framework!
Another great piece to think about:
MVC is not an Architecture! It is a Delivery Design Pattern.
Watch his video - it is one of the sadly few ones out there that don't spend 1000 words on what can be said in 10 and I can't highly enough recommend it - and it will help you to understand many points raised in your question:
Robert C Martin(Uncle Bob) -Clean Architecture and Design - Video
Of course, his book on Clean Code is also highly recommended!
Although this link is for Laravel 4 docs, it may help you understand how the models work - (Laravel 3 also uses Eloquent):
http://laravel.com/docs/eloquent
Also, specific to laravel 3:
http://codehappy.daylerees.com/eloquent-orm
Related
Note before we start: I've asked this question on the Phalcon forum as well as here to try and broadcast the question a bit wider.
Following on from a question on the Phalcon discussion board by jasmad...
I am in the process of migrating an application from CodeIgniter to Phalcon, and I'm looking with eagle eyes (pun intended) at the models, which to me seem the easiest place to start (as well as having the biggest performance improvement for my project).
Are there any kind of tutorials/guides to migrating models from CodeIgniter to Phalcon knocking about? Has anybody got experience in doing this that they'd mind sharing?
I've got a shedload of queries that look like:
$this->db->select("a.*")
->from("tableA a")
->some
->other
->conditions;
$this->b_model->join($this->db, "a.idB")
and b_model might have a fn like this:
function join (&$db, $col) {
$db->join("tableB b", $col . " = b.id", "left");
->select ("b.*");
}
Those are much simplified versions I've just typed up for conciseness, but hopefully it'll give an idea what I'm trying to achieve.
Just as a note, I don't want to use the in-built Phalcon relationship doodahs for reasons that are longwinded and will detract from the focus of the post. I just want to change those queries in to a PHQL query builder thing, also utilising some existing libraries & helpers that the CodeIgniter models use.
Anyway, yeah, is there some kind of guide for folk wanting to migrate? I don't mind writing up my experiences if there isn't, but it's always nice to have a guiding hand from someone who's done it before ... :)
model manager is one of service in phalcon, so you can add your model manager to dependency injector taken from cakephp and have all your old queries working fine. Of course, if you want to use phalcon's models, i wonder if you would be good to go without changing your code.
First of all, Everything is kind of confusing. There is a few tutorials and complete documentation but i feel like something is just not working way it should. For now I'm a little bit confused and discouraged. I learned how to write forms, how to make views with blade. How to menage migrations and even seeds. I know how to create new controller and simple routes.
But guys... I need some advice if you would answer...
I created a form with a view for example that form:
{{Form::open(array('url' => 'person/confirm'))}}
{{Form::label('firstname', 'Firstname:')}}
{{Form::text('firstname')}}
{{Form::label('lastname', 'Lastname:')}}
{{Form::text('lastname')}}
{{Form::label('company_name', 'Company name:')}}
{{Form::text('company_name')}}
{{Form::label('mail', 'Mail:')}}
{{Form::text('mail')}}
{{Form::label('phone', 'Phone:')}}
{{Form::text('phone')}}
{{Form::label('additional_phone', 'Additional phone:')}}
{{Form::text('additional_phone')}}
{{Form::label('city', 'City:')}}
{{Form::text('city')}}
{{Form::label('postalcode', 'Postalcode:')}}
{{Form::text('postalcode')}}
{{Form::label('address', 'Address:')}}
{{Form::text('address')}}
{{Form::label('notes', 'Notes:')}}
{{Form::text('notes')}}
{{Form::submit('Submit')}}
{{Form::close()}}
Nothing fancy, just a basic form. If I call submit, it will take me to person/confirm route. And it will be like this:
Route::post('person/confirm', function(){
$input = Input::all();
DB::table('humanity')->insert(
array('firstname' => $firstname);
);
}
I know that it is wrong.
How to get values from $input?
How to insert it to table correctly and safely?
Where is the best place to make query call?
It will be better to make query before routing starts or when next route will execute?
It would be good to create query in controller function and execute it in route then redirect to "message: Success"?
What exactly are classes and models and how can I use them?
I plan to write some system and day by day it makes me more sicker than satisfied. Something call me that I had hitched my wagon to a star.
Thank you in advice.
It looks like you're in way over your head, especially since you asked what classes are.
I'd suggest putting Laravel (or any framework, for that matter) aside for a while until you have a solid understanding about object oriented programming and architectural patterns such as MVC / MVP. While Laravel resources will improve your knowledge quite a bit, it won't be nearly enough to create well structured applications.
Here are a couple of books that might be useful:
PHP Objects, Patterns and Practice
Clean Code: A Handbook of Agile Software Craftsmanship
Ok so first off I suggest you look into Eloquent. Laravels ORM (http://laravel.com/docs/eloquent).
Eloquent will allow you to do this:
$human = new Human(Input::all());
$human->save();
But we can come back to that, your first question here is how to use the Input class.
The real documentation can be found under Requests in the laravel documentation, but here's a brief guide.
Input::get('firstname'); //gets the first name
Input::get('lastname'); //get doesn't refer to the method, "get" will retrieve from post or get.
Input::all(); //will get you all input as an array - don't forget to validate
Input::except(array('csrf_token')); //will get you everything except for the 'csrf_token' as an array
One of the best ways to get help with Laravel is through the Laravel IRC channel, the community is great.
#Laravel is a place where many developers hang out and discuss the framework. Many people frequently pop their heads in looking for some
help.
But, the real-time chat nature of IRC can be a refreshing contrast to posting on a forum and waiting for a reply.
The official community hub for laravel
Laravel.io has forums along with a plethora or useful tools such as the pastebin, you should become friends.
The other resource I suggest is Taylor's book
It's not free but it's well worth it.
Written by the creator of Laravel, this is the definitive guide to
advanced application development with Laravel 4. Learn about
dependency injection, interfaces, service providers, SOLID design, and
more while exploring practical, real-world code examples. Whether
you're building a robust, large application with the Laravel
framework, or just want to sharpen your software design chops, this
book will be of great value to you and your team.
What I'm looking for is a way to remove the model from a set of PHP files that make up a website. It's difficult (for me) to explain.
By models I mean models in an MVC sense.
As an example say I have this website:
index.php
about.php
shop.php
checkout.php
All of the above PHP files use the same database. I have separated the views by adding templates using a view.php file that renders the correct template with values passed to it.
I am not looking to use a framework that's already out there. I'm looking at writing my own in some senses, with only the bits I need to use in it.
If anyone would like to explain why this is not necessary, or a better way of doing things, then I'm open to that too.
Thanks in advance.
Writing you own MVC framework will take time, but you will learn a lot in the process. So, if you have the time/resources to do it I definitely encourage you to do so.
In this context here are some small pieces of advise that may help you:
Create your domain model first. I'm assuming that you are going in the OO way, so think about your domain problem and create the abstractions that best represent your problem. Try to keep it decoupled from cross-cutting concerns, like persistence.
Test a lot, test often. Try to test (and run your tests) as you create your domain model. This will be specially valuable when in 6 months you add a new feature and want to make sure that you haven't break anything. If you can separate your domain model from anything external (like the persistence layer or third party web services) the testing it is going to be a lot simpler. Today PHPUnit is pretty much the de-facto standard for unit testing in PHP.
You don't have to write everything from scratch. There are a lot of libraries that can help you to ease the development of an MVC framework, so that you can concentrate on what you really want to develop. For example, you could use Slim to handle the page routing or you could delegate the persistence stuff to Doctrine 2.
It is always nice to analyze how other frameworks solve things. You may want to look at products like Symfony or Kohana or even check how Elgg handles its views system. Also, if you want to check out something radically different you can take a look at Seaside's architecture.
Coming back to your original question, for me the key is to keep things from different layers as decoupled as possible. While I have only used the version 1, Doctrine 2 seems like a good candidate for persistence, since it allows you to create a domain model that is quite independent from the DB. This is a huge step. The second thing is how handle the view system. This is quite developer-taste dependent. For example, I like to model everything with objects, so I like Seaside's approach. On the other hand, Elgg's way of handling views is quite nice and maybe fits better with the way things are handled in PHP. Here is when you may benefit on doing some research before deciding on a route to go.
HTH
As someone who has written his own PHP framework, and with the same sensibility as yours, I can tell you that using a framework is a fine thing to do. That said, start by writing your own - you'll gain greater appreciation for the true structure and utility of a framework.
You'll want to learn about the Singleton object pattern. It is a major differentiator in the kinds of objects you can develop in your framework.
When you have written a few models that your files/controllers (presuming MVC) include, you will begin to see where to abstract a 'base mode' from which others extend (hint: the DB singleton).
When you start pulling in configs and the like, then you'll have your first framework object from which all other bases do their extension.
i have a project i took over. it is an app that has been build over many years with PHP and mysql.
It currently has a sort of good folder structure but the code itself is very poor written.
There is php, sql statements and html code in almost every file.
There is javascript code generated using php echo for not reason and so on.
I will like to use for further development either CakePHP or CodeIgniter, even if that means that for the new features some code will be written that already exists (eg.: maybe utility functions) in the old code.
is it possible to integrate one of these frameworks into an existing app?
which one is easier?
do you have any links on how to do it?
thanks.
I have very little experience with CakePHP so my answer is going to be about CodeIgniter. I played with CakePHP for about a day and that was almost two years ago. In my opinion it will probably be easier to integrate with CodeIgniter although someone more experienced with CakePHP might prove me wrong.
Here is the approach I would take. I have never done this, but it seems like a logical way to approach the problem. I suppose this approach would also work with CakePHP.
First, start with a fresh CodeIgniter install using the latest version.
Next, create controllers and actions (controller methods) that mirror the current structure of the application. For example, if you had a page with the URL http://example.com/users/view you would create a Users controller with a view() method.
Next, create view files for each of the current files of the application and load them via the appropriate controller methods. The goal here is to get the application working using CodeIgniter's routing system although at this point you won't be utilizing any models, libraries, or helpers.
Once you have the application sitting on top of CodeIgniter, start refactoring it to fit into the MVC pattern. Pull out application logic (queries, form handling, etc...) from the view files and place them into the controllers. Keep all presentation logic and HTML in the views.
Next, refactor the controllers. This is where it gets tricky because controller code can be placed into models, libraries, or other controller methods. A good starting point would be to take all of the queries and put them into appropriate models. Compare your controllers and see if there is any code duplication. That is a good sign that you should remove it from the controller and place it elsewhere. Unfortunately I can't really tell you where because it differs in each situation.
Continue refactoring your application until you have it in a workable state that you are pleased with...
Hopefully this helps. I certainly missed some critical steps such as setting up and configuring CodeIgniter but if you're serious about doing this I would highly recommend reading through the CodeIgniter User Guide to get a good idea about how it works. You should also get familiar with MVC (model-view-controller) if you aren't already.
There's not really a one size fits all solution here but hopefully I've given you some ideas or at least a starting point to jump off of. If you have any questions or are a little confused drop a comment below and I'll get back to you.
In my opinion, it's easier just to write your controllers in CodeIgniter (I've never used CakePHP) and models, than you just copy paste with some adjustments the views.
I've recently inherited a medium-sized php site which is horribly coded. It violates every best-practices methodology, from MVC to DRY, is vulnerable to SQL-injection and everything in between.
I've visited the other questions and already put everything on a VCS and am considering the framework alternatives. However I'd like your opinions on a framework that lets me slowly migrate from the actual site to a framework controlled one.
Thanks.
Zend Framework would actually be the best choice in my opinion, as it has a great use-at-will structure and it is no full-stack framework like most of the others.
That means that you can start with migrating the model-layer first without having to touch the view or controller part. And even when it comes to the controller part, you could first put everything into controllers without having to rely on the router, so you could still use your old URLs.
I will put my vote in for CakePHP (http://www.cakephp.org). It has the ability to manage everything very nicely.
Template
This will allow you to create the base template / layout for the site. It is the main body of the site. You can store multiple layouts all in the views/layouts directory. You can identify what layout you want to use for any given page within the site.
Static Content
If you have static content pages, they all reside in views/pages. These will load into the layout wherever you put the <?php echo $content_for_layout; ?>.
Custom Code
Many times, you will have custom code that may not fit in the framework. No worries, you can add this to the libs or vendors folders and call the functionality from there.
Speedy Upgrade Via Bake
One of the cool features of cake is the bake feature. Once you have added your schema to the database, you can use bake to have CakePHP write all of the models (with relationships), the controllers (with basic CRUD and admin sections), and the views for each action within the controller.
Cake has been a great fit for all of the projects I have worked on. It keeps the code well organized, has a very active community, and their documentation is very well written and understandable.
UPDATE: For additional information about some sites who use cakephp you can see a sample list here: http://book.cakephp.org/view/510/Sites-in-the-wild
A few notable (high traffic sites) would be:
https://addons.mozilla.org
http://scratch.mit.edu/
Kohana is my framework of choice, but I won't start to wax about its good points, I'm sure it can do anything the others can do.
Faced with the same legacy codebase problem as you described, my response was to take Kohana and disable the request routing, so that you can just use it as an include on a page-by-page basis until you're ready.
The changes are minimal; if you're interested the fork of kohana is up on github
You may need to adjust the php error level settings depending on the kludgey-ness of your codebase ;)
Zend Framework is awesome.
Even better, this excellent post from Chris Abernethy shows how to gradually migrate an existing site from a twisted plate of pasta into a nice MVC structure using ZF.
Take a look at Fat-Free Framework. It allows both procedural and OOP code, so you can have a two-stage approach. If the base code is currently procedural, then you can focus all efforts first on transformation to MVC architecture. That way you can have a proof of concept that all future efforts can be as fruitful as the first phase. Then you can move too strictly-OOP. No other framework will give you this kind of flexibility. And your end-users will not feel any delays, or worse, a culture shock.
You will get as many answers as framework users there are in this place. It's obvious that someone using framework of his choice will advice it to the others.
I opt for symfony.
However, if you care about best practices than both symfony and Zend are a good (and only) choice.
This sounds like a massive undertaking.
I can only recommend CakePHP because that is what I use, but that does not mean another framework would be less or more suitable. They're all pretty much the same when it boils down to it.
Choose on whatever criteria you wish, such as public support/user base (Cake's is massive), feel, name, colours on the webpage, whatever. But my advice is to stick with that choice and ride the learning curve.
All the frameworks mentioned are good, but you will need to rewrite loads of things like the queries. You might not want to use an ORM like Doctrine or Eloquent. Just stick with something like Active Records. Codeigniter, CakePHP and Yii will do just fine.
but it is not going to be an easy task. be warned!