CodeIgniter: what makes a good model - php

What makes a good MVC model in CodeIgniter. What my 'user' model does now is basically using the same active record functions from the database library. The only difference is that you don't need to specify the database table and just do:
$this->usermodel->where('username','test'),
$user = $this->usermodel->get();
This feels kinda awkward, since its not making it 'a lot easier'.
Another way I thought of was making the user model like an user object with a load function. But this is not efficient when loading more than 1 user.
Can I get some tips from you guys? Thanks.

A good tip would be, not letting model an view talk with each other straight, you always(or when it's possible) have to use controller to do this kind of communication.
I've heard also the opinion that it's a bad practice to have logic inside your models...I don't know if this is true but it's a rule I have broken lots of times(if somebody knows more about the subject please correct me).
And of course always have in mind that model should be reusable , so I try to give general solution to some problems and not application specific...on the other hand controller seems to be the throwaway component so this is where you should do ugly stuff that will never be used in other projects...
Hope it helps a little

I think 'a lot easier' comes in when you are working with large sets of data, and have many complex queries to make. As I understand it, if you are working on something that is relatively simple, you can forego the model and make your db calls from within the controller. There isn't a 'best practice' per se, but rather personal preference.
The MVC architecture allows for better compartmentalizing of code, and can allow for better structure and re-use of code, but you needn't follow the MVC idea to the letter to accomplish many things -- again it comes down to preference.

The point is to abstract all of your application logic into Models and use Controllers simply for 'controlling' your web interface and mediating between the web interface and the models.
The models are your program proper you should be able to pretty easily completely redesign the user interface without affecting the application models.

Related

Is there a (simple) way to separate models in pure PHP, and what is a good way of doing it?

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.

Lithium apps that go beyond CRUD

This is more or less a framework-centric version of a past Stack Overflow question, which is about how most introductory material on MVC applications tends to present a tight coupling between models, views, and controllers. For example, you'll have a User table that is modified by a User controller which in turn pushes filtered data to a User view. It's my impression that a lot of MVC frameworks tend to reflect this pattern as well. This is all fine and well for what it is, but it never really leads me to anything beyond building and displaying monotonous lists of things with an HTML form.
The MVC framework that looking at right now is Lithium, which seems quite interesting as a case study of clever PHP5.3 coding techniques. On one end, Lithium has a Model class that offers wrapper objects around a individual tables, and abstracts away some simple queries. On the other end, it's got a nifty convention of routing URLs to method calls on controller objects, which then render to display templates.
But in the midst of this, I find myself at a loss as to where to place all of the interesting logic that relates data in table A to data in tables B through Z. Or at least, I'm not sure where to place such logic in a manner that's consistent with the design of the framework. To my understanding, Lithium's Model abstraction doesn't do much more than eliminate some row-level insert/update/delete boilerplate, and the controller/view architecture seems mostly about user interface. I wouldn't want to put a lot of business logic in the same Controller class that is receiving routed function calls from URL requests.
My instinct would be to fill the gap with a bunch of my own code that exists more or less entirely outside of the framework. I'm not sure if I ought to expect more than that, but given how rigidly structured everything else is in Lithium, it feels somehow unsatisfying, like I could have just rolled my own boilerplate-reduction code without the overhead of grokking the source of a big framework.
What am I missing here? Is there a recommended architecture or philosophy to using this type of framework?
One thing you have to remember with Lithium is that theres no production ready release yet (although some sites are using it in production).
The main missing feature right now is model relations. With relations in place i assume your question would be partially answered as that is an important brick in the big picture of creating more complex applications.
You could check out the x-data branch where the work on relations should be ongoing.
For the second part of writing domain logic the simple answer is "in the model".
See this (rather useless) example of extending model functionality for example.
Another example to look at is the open source mini application Analogue that is one of the few working open examples of Lithium in use. The Analogue model class shows a slightly more meaty model.
And finally its a matter of connecting the dots between M, V and C.
A Lithium controller should mainly delegate jobs over to models, and perhaps restructure the input data if needed.
The simple examples of having a Post model, PostsController and views/posts/add,index,etc doesn't mean that you have to merely have Post::all() in there.
PostsController::view need to load a set of Comment models probably.
So you will toss a lot of your own code in there, of course! Else it would not be much of an application. But keep the domain logic tied to the model where it is natural.
Need to verify that blog post has a
unique title? Write a validator.
Need to ensure the user has write access to the post? Override the save method and verify it, or filter it.
But I think we need to wait for relations to land and a 1.0 release before we can fully judge how structuring applications in Lithium can be solved best.

Simple DB Model

I do not have much experience using frameworks or anything so that leaves me with little experience using Models (MVC). I have no interest whatsoever in using a framework at the moment. I am working on a website and I am trying to model some objects but I'm not sure exactly how I should be designing the class.
For instance, right now I have a class with a few public members which can be accessed directly. I have started prototyping some functions (select, delete, update) but I am not sure
If these functions should be static
If these functions should accept parameters or use the class members instead
If these functions should even exist how they do currently
If the entire concept I'm going for is the right thing to do
I can't seem to find any sort of hints on the interwebs as to how to create a model class.
If you're using a factory class then all verbs are usually instance methods and the factory is instantiated with some sort of DB session.
If the verbs are member's of the entity's class select is usually a static method while update is usually an instance method and delete is usually defined both ways (IE: delete(recordID) and entity.delete())
The entire concept is the right thing to do but you're going to do it wrong. Period. Making a scalable model like this takes a lot more time and effort than people have at their disposal. I know you have no interest in using a framework but you should.
My inference from your question is that this is a low profile project, and you have enough flexibility from your boss/client/teacher that you can build it however you want. That in mind, here is what I would think about when working on this.
If MVC is a new concept to you, then Test-Driven Development is almost certainly and alien one as well. However, I first cracked into a real understanding of OOP while doing it, so I suggest you give it a try. Writing some simple unit tests first against your model classes will take you through the exercise of figuring out how those model classes are going to be used. You'll be working with the external API of each of those objects (or groups of objects if you're not a TDD purist), and that will help guide the design of the internals. Check out PHPUnit for getting started, as the documentation has some great examples as well.
I think the TDD approach will lead you to the following conclusions:
Probably not. Static data/methods are usually only useful when you absolutely need one copy of something. I find in web apps that aside from maybe a resource connection like the DB this is rarely the case.
This depends on what the function does. Keep in mind that using local variables implies side-effects, or changes in the state of the object. If the data you need to operate on should not change the state of the entire object, use a parameter and return a value. It's also easier to test these kinds of methods.
Again, writing tests for these functions that illustrate how you'll use them in the application will lead you to a conclusion one way or another about whether you need them or whether they are designed correctly. Don't be afraid to change them.
Absolutely. How else are you going to become comfortable with MVC if you don't roll your own implementation at least once? In fact, it's probably better to grasp the concepts with real experience before you move to a more professional framework. That way, you'll understand why the concepts and conventions of the framework are the way they are.
Oh, and the lack of clarity that you're finding on what a model class is, is probably due to the fact that it's the part of your application that is most customized. This is your data model and domain logic, so a lot of it is case-specific. The best resource, though, IMHO is Martin Fowler, whose excellent book Patterns of Enterprise Application Architecture goes into a lot of detail on how and why to design a particular set of "model" classes with one pattern or another. Here is the online pattern library--obviously the book is more detailed.
Hope that helps somewhat.
When using PHP, I think designing object oriented model adds extra work with little benefits - even when looking on large frameworks, it's common to just use assoc-arrays that you can get from resultsets (see f.ex. the multiparadigm approach of Zend MVC).
While Object-Relational mapping is much more established among strongly typed languages like Java, there are already tools for PHP as well (f.ex. Doctrine). You may check it out if having OO-oriented model is what you want, but be aware that OR-mapping has severe issues of it's own and might be of little use in PHP (haven't tried it myself in a dynamic language yet).
For most newly started project, picking a good framework is usually a way to go - it can save you time and promote best practices (of course after some learning time that's different for every tool out there). When using some framework, you should always try to find out the framework's / community approach to solving specific problems (like model design & data access) before experimenting on your own.
The "correct" way to abstract away data access using object-oriented concepts is a hot-button topic for a lot of people. Put another way, there are several ways to do it and there is no "one right" way.
Rolling your own works best if you are seriously upgrading an existing application. This is because you have a heap of code that is already database dependant and you have some bounds for the necessary refactoring. It also teaches you about abstracting code because a lot of refactoring involves removing (or reducing) code duplication. Once you've done this to completion, you will have a much better idea of how a data model layer should work. Or at least, should work for the way you program. And you will know what not to do next time you build one. :-)
If you're starting a new codebase and haven't worked with a framework or object layer but know you need to build one, then the best advice I can give is to be willing to build one later, and refactor the code to suit when that does happen. Yes, it will likely mean your application will get 90% rewritten a few times.
Writing an object abstraction layer is difficult and you will end up with dense code that is fairly defensive about things, and doesn't take chances. But once you've got it working, you will also know how to build robust code, because it will probably be debugged fairly thoroughly.
No because, static methods are hard to test
It depends of the parameter, life cycle, etc. Impossible to answer without seeing some code.
?
No
OOP requires at least 10 years of experience to have a better view on what is wrong/right/better/worse.
So, if you are not a OOP expert, instead of losing too much time reinventing the wheel, I would suggest:
Use a well-known framework for the technical part
Create your classes/framework for the business/functional part.
(1) Will help you be ready in no time for the classic technical part (Session, database interaction, etc.). Will avoid you to make errors others already did.
(2) This is your core business, it should be "your DNA".
Also, using a well-known/good technical framework will make you read quality code and help you progress. (Be carefull some frameworks are really of poor quality)
When you will have enough experience, you will be able to skip the technical framework part and build/customize your own... because technical framework are usually evil (They serve too many purposes). :)

What is the best class structure for simple php framework?

I am trying to create simple php framework .But i am not sure about class structure for example which classes should extend to which classes .Firsly i am know that some basic classes such as Router , View classes have to access some basic data such as requested url or requested ccontroller and action so how can i import basic data to these classes .If my question is not clear please explain your own experiances and ideas about frameworks.or if you know please talk about known framewoks such as zend , cakephp or symfony
There is no best class structure. Depends on what you are trying to do. Do you mean purest MVC design? Most testable? Most easy to understand?
There is a simple rule of thumb:
Either you have a need that the standard frameworks can not fulfill
or you should use a good standard framework that does what you need.
In the first case the restriction will be the driving aspect in your design.
There are no general design rule for class structures in frameworks. But try to keep this in mind, if you decide to write your own one:
Minimize dependencies between modules
Always try to give default values
Try to minimize the overhead
Talk a lot with peers about it to find flaws early.
If you've never worked in someone else's framework you will have no idea what ideas work for you and what don't. If you've only ever worked with dis-organised spaghetti code, then you will have some idea of what makes sense for you. If you've made substantial re-organisation to dis-organised spaghetti code in more than one unrelated project, you should have a good idea of how you think in building a framework. :-)
If you don't have a firm idea of how you want to write a framework, but you want to write one, I think you need to start with nothing and build it organically. However, you should have some idea how you want it to look like, even if it's something as silly as where you want the include files to live. In other words, all you need is a starting point. Then it's a matter of re-factoring ugliness as you encounter it. Before long, you will have a database handler, a dispatch mechanism, perhaps a data access layer, just maybe even a templating system!
Responding to #MrFox, though, you should be aware of dangerous dependancies. Obviously a data access layer will depend on a database handler; so what you don't want is for your database handler to depend on your data access layer. In fact, you don't want them to have intimate knowledge of each other, either. It should be a reasonably "black-box" interface.
Also, a number of frameworks try to build "one" object heirarchy. This means they think an Action is-a Model is-a Database Handler. I personally have problems with this mis-applied abstraction, so this is a heads-up to not be afraid to spurn this idea if it doesn't work for you, either. As #Tyndall said, there's no one, single "right" way to do it.

is my php architecture solid?

I'm trying to design a solid server side architecture and came up with this :
http://www.monsterup.com/image.php?url=upload/1235488072.jpg
The client side only talks to a single server file called process.php, where user rights are checked; and where the action is being dispatched. The business classes then handle the business logic and perform data validation. They all have contain a DataAccessObject class that performs the db operations.
Could you point the different weaknesses such an architecture may have? As far as security, flexibility, extensiveness, ...?
Your architecture isn't perfect. It never will be perfect. Ever. Being perfect is impossible. This is the nature of application development, programming, and the world in general. A requirement will come in to add a feature, or change your business logic and you'll return to this architecture and say "What in the world was I thinking this is terrible." (Hopefully... otherwise you probably haven't been learning anything new!)
Take an inventory of your goals, should it be:
this architecture perfect
or instead:
this architecture functions where I need it to and allows me to get stuff done
One way that you could improve this is to add a view layer, using a template engine such as Smarty, or even roll-your-own. The action classes would prepare the data, assign it to the template, then display the template itself.
That would help you to separate your business logic from your HTML, making it easier to maintain.
This is a common way to design an application.
Another thing you could do is have another class handle the action delegation. It really depends on the complexity of your application, though.
The book PHP Objects, Patterns and Practice can give you a real leg-up on application architecture.
I see a couple of things.
First, I agree with others that you should add a view layer of some kind, though I am not sure about Smarty (I use it frequently and I am really having doubts these days, but I digress). The point is you need to separate your HTML somewhere in a template so it's easy to change. That point does not waver if you use a lot of AJAX. AJAX still requires you (usually) to put divs around the page, etc. So your layout should be separated from processing code.
The second thing I would throw out there is the complexity of your data model matters. If this is a straightforward CRUD application over an existing, or fairly flat, db model, you are probably fine with these db access classes. But, the minute your model gets to be more complex, with hierarchies or polymorphic in any way, this will break down. You'll need a more robust ORM of some kind.
Your "controller/dispatcher" methodology seems sound. The switch statements avoids the need for any kind of URL -> code mappings, which are a pain to manage and require caching to scale.
That's my $0.02
From a security perspective your class and action are coming in from your post variables and this can be dangerous because you should never trust anything coming from the user. Assumingly your class/action will look something like this:
class1
{
action1.1
action1.2
...
action1.N
}
class2
{
action2.1
action2.2
...
action2.N
}
As an attacker my first place to look would be getting into a state where an action doesn't match to it's appropriate class. I would try to submit class1 with action2.1 instead of action1.1.
With that said, my assumption is that you've already got some form of validation and so this wouldn't happen. Which leads me to my original post: If your architecture works for you, then it works for you. Take a look at the things which you're asking about: security, flexibility, extensibility and evaluate them yourself. Find your own flaws. If you don't know how to evaluate for security/flexibility/other read up on the subject, practice it and apply it.
You'll become a better developer by making mistakes and then learning from them (except missile guidance software, you only get one try there.)
Since others have suggested various changes like adding a view layer, etc. let me concentrate on the various criteria for a good architecture:
Extensibility: Usually, the more abstract and loosely coupled the architecture is, the more extensible it is. This is exactly why others have recommended you use a view layer which would abstract out the presentation layer templates for each class:action pair into its own file.
Maintainability: This goes hand-in-hand with extensibility. Generally, the more extensible the architecture is, the more maintainable it is (take that with a grain of salt because it is not always the case). Consider adding a model layer below your model logic layer. This would help you swap out your data access logic from the model business logic.
Security: The downside to the architecture you have posed is that you really need to invest in security testing. Since all your redirecting/routing code is in process.php, that file has a lot of responsibility and any changes to it may result in a potential security loophole. This isn't necessarily wrong, you just need to be aware of the risks.
Scalability: Your architecture is balanced and seems very scalable. Since you have it broken down by class:actions, you can add caching at any layer to improve performance. Adding an addition data access model layer will also help you cache at the layer closest to the database.
Finally, experiment with each architecture and don't be afraid to make mistakes. It already seems like you have a good understanding of MVC. The only way to get better at architecting is to implement and test it in the 'real world'.

Categories