How coarse grained should the model be in an MVC framework? - php

I have been reading a few questions previously asked and I haven't come across one that answers my question in "black and white" for me! So, apologies if this is repetitive. The question is probably similar to asking, "how long is a piece of string" but bear with me!
For a registernation system, I have a user model with functions such as:
add_user
delete_user
activate_user
The above user model deals with one table. The users table in the MySQL database.
You can guess what each function does but is this coarse enough? I mean should my model contain methods that are much broader such as:
add_record
delete_record
update_record
Where I pass in the table and a unique identifier of the record to delete, add or update?
I am using codeigniter, but I am interested in how things should be done in a pure MVC framework.
I apologise if this question is too picky.
Thanks all

I'm not sure what you mean by "coarse".
"should my model contain methods that are much broader such as: add_record, delete_record, update_record"
Absolutely not. Never. That defeats the purpose of having a model.
That kind of "general-purpose" stuff is what a database is for. The point of a model is to adapt the general database to your specific problem.
Your model should be specific to your problem.
"user model with functions such as: add_user, delete_user, activate_user" That's the point. Your model reflects your application, your problem domain, your solution.
Your model should be able to -- in effect -- stand alone. You should be able to wrap your model in a command-line app or a GUI app or a web page.

You can guess what each function does
but is this coarse enough. I mean
should my model contain methods that
are much broader such as:
* add_record
* delete_record
* update_record
Where I pass in the table and a unique
identifier of the record to delete,
add or update?
If you have a need to get only the information of a user doesn't necessarily make use an entire record, then it is just right for you to have *_user functions, but include it only in your user model.
If you have a need to get an entire records instead of just the user, then it is also just right for you to have *_record functions, but put it in your record model - NOT in your user model.
The thing to remember here is to not include all of those functions in just one model. Simply put, your user and is the same as a record.

Related

Laravel + MySQL - Storing Eloquent namespaces

I was given this project to work on with absolutely no documentation or contact developer. I noticed in the database dump that they are storing what looks like PHP Namespaces for Eloquent models in a couple tables. For example an address table has a string column named "object_type" with the value always being "App\Entities\Client". I searched through the whole project for the PHP code that would use this value. Hopefully to give me insight to it's purpose. Not to my surprise, the project never uses this value. I just see it hard-coding these values upon insert into the DB.
My question is, is this some sort of Database and/or ORM modeling design practice? If so, could you explain how this could be used in a simple practical sense?
Maybe this was some concept the developer had and it never evolved. It's interesting idea but, the idea of joining through MySQL on a string conditional sounds like torture.
Sounds like Laravel polymorphic relationships:
Custom Polymorphic Types.
By default, Laravel will use the fully qualified class name to store the type of the related model.
And, yes, this is a valid modeling technique, though purists rightly argue this technique abuses normal form.
I am not sure what the developers where thinking.
But imagining we are in a forum with thread and replies to each thread. We maybe want to have a Favourites table where we can save replies and threads.
A way to do it would be to have a column in the favourites table called "object_type" (just to use the same term you have in your case) and then when we save an object into the database with eloquent we can use:
$favourite->object_type = get_class($thread); //or get_class($reply) in case we want a reply
$favourite->save();
This way will save the namespace of that class into the database. But laravel will recognise it when we get it from the database.
Hope this cold be helpful.

laravel do I need a Model and Controller for every single table?

I know this is a duplicate question but i think it will help others because there are a lot of similar apps that have these kind of table relationships:
So the question is what would be the optimal solution for all relationships in this schema using the Eloquent?
How many Models and Controllers to make?
First of all, you need to understand that not all tables in a database represent an entity.
For example, tables like users, posts, comments are entities. Whereas posts_users, comments_posts are not: they are here for technical reason, to materialize the relation between 2 entities.
Only entities need a model: it makes no sense to have a model for a relation table.
Even if a table holds information like date_created, it does not make it an entity. This is just a data related to the relation. For example, the table users_roles may have a column named date_assigned, to know when a given user was assigned a given role. It's not entitity for all that.
Second, you need to understand what a controller is for. The role of a controller is to handle a request and provide a result. Result can be a view, an error (HTTP 404), or just the fact that an action has been successfully done.
You must also make the difference between the class called Controller (or any child that extends this base class) and an actual controller. The actual controller is the code that will handle the request. A Controller class can have more than one method to handle requests.
It's all a question of organization: generally, Controller classes are used to group methods within the same scope: user login, logout, subscription, password reminder are all the same scope. All these controllers could be in different classes or functions. It does not matter. Each method is a controller. They are grouped in the same class because they have the same needs (check user is logged in, to know if login is required, if subscription page can be displayed, etc.) and they are in the same scope, which just make sense when you think of it. That's just logical: you know where to search when you need to change something about user identification (even if you are new on the project).
So you need a model for these entities:
User
Offer
Invoice
Category
The controllers you'll need depends on what you want/need to do with this data. There's no ready-to-use answer to this part of your question.
Use a Controller class for:
user authentication (if you need some)
user management (backoffice)
invoice management (edit, mark paid, list of late payments, etc.)
categories management (create, edit, delete)
offers management
But depending on your application, you may need more. Only you can really say. There's no bad answer to this question: if you think some controllers should be separated for better organization, do it. If you think you should group 2 or more, do it. There's no rule. You have to keep your code clear and well organized. It must suit your needs. That's all.

Why is $uses considered bad practice in cakePHP?

I have 3 tables that contain user information, one for students, one for teachers and one for administrators.
They are not related in any way. I wan't to create a dashboard for the Administrators, where a list of students and teachers shows up.
The only way I found to achieve this was using the $uses variable in the Administrators controller. However, I have read in many places that this is bad practice.
Any solutions?
Another, perhaps better practice is the use of ClassRegistry::init('MyModel')->myMethod() (more reading # Cake API)
This only loads the object when it's used, as opposed to loadModel or uses, with ClassRegistry the models are treated as singletons.
--
that you are doing something wrong: you need access to a model that has nothing to do with your current controller.
There are plenty of conditions where you would need to access all of your models data, from one controller, but never a definitive answer on how to do it without breaking convention!
You can always use another Model which is not related by using
$this->loadModel('NewModelName');
Then you can access new loaded model by:
$this->NewModelName->add(); // whatever method model has defined
Why prefer loadModel() over uses?
To gain performance. How? uses calls the loadModel function itself to load all the models you specify in uses array. But the problem is if only one of your action needs a particular model, whats the good thing to include it in every action. e.g. only add() action requires an unrelated model, but if you have specified it in uses array, no matter what action gets called a completely unrelated model is going to load. To put simply it will be inefficient. Its like you have declared variables in a C programme but never used them. In case of C compiler will warn you that you are not using your variables, but unfortunately cake couldn't tell you.
Its alright to use uses if all your actions needs to load that model, use loadModel() otherwise.
You probably didn't read my answer in your other question :))
I have 3 tables that contain user information, one for students, one for teachers and one for administrators. They are not related in any way. I wan't to create a dashboard for the Administrators, where a list of students and teachers shows up.
The problem is you are separating similar data into 3 different tables, in this case, user information. So when you try to manage this data, you hit a brick wall: because you leave out the relationships when you separate them in 3 tables.
The only way I found to achieve this was using the $uses variable in the Administrators controller.
You got the wrong idea about the controller. Each controller manage the data flow of a particular model (and related models). It doesn't mean that you have to stay in Admin controller to do administrative things. What model you want to manipulate decides what controller you need to be in.
However, I have read in many places that this is bad practice.
Now for the main question: using $uses is a red flag that you are doing something wrong: you need access to a model that has nothing to do with your current controller. Now, there're always exceptions in programming, sometimes we need to have access to that model. That's where loadModel comes in. Because it should be rare. If you need the model a lot, then you'll need to call loadModel a lot, which is cumbersome, which is what $uses is for, but then that means something's wrong with your app design :))
So, you can say using $uses is a sign of bad decision (in DB design or application structure); and so is using loadModel a lot.
Edit: Any solutions?
I gave one solution in your other question. But if you want to have them all in one place, you can have 1 users table with user information. Each User can hasOne Student, Teacher, Administrator and a 'group' field to decide what group the User is. The third solution is using $uses. Its performance impact won't be a problem really. But it will be pretty convoluted when you develop your app further. That's what you need to worry about. For example, I can say that, if you use Auth, you'll need to tweak it a fair bit to get it working with 3 models. If you use the users table, it will be a lot easier.

PHP framework URL conventions

A lot of frameworks use URL conventions like /controller/action/{id} which is great, but if you need any configuration beyond that, it's up to you to write your own routes.
How would you handle URLs like /users/{id}/friends on the backend? (to list all of a user's friends)
I'm thinking that in the controller, something like this would be appropriate:
class User {
function index() {
echo 'user index';
}
}
class Friend extends User {
function index($user_id) {
echo 'friend index';
}
}
Then you would have the following map:
/users -> User::index()
/users/{id} -> User::view($id)
/users/{id}/friends -> Friend::index($user_id)
I wanted to put the Friend class inside the User class but apparently you can't do that in PHP so this is the best I could come up with. Thoughts?
What URL would use for editing your list of friends? /users/{id}/friends/edit could work, but it doesn't seem appropriate, since you should never be editing someone else's friend list. Would /account/friends/edit be a better choice? Where would you put the corresponding code for that? In a friend controller, or a user controller, or a specialized account controller?
Bonus question: which do you prefer? /photos/delete/{id} or /photos/{id}/delete
The answers:
So, what I've gathered from the answers is that if the "thing" is complicated (like "friends") but doesn't have its own controller, you can give it one without a model, or if it's not, you should stuff it in with whatever it's most closely related to. Your URLs should not influence where you put your code. Most people seem to think you should stick to /controller/action/{id} whever possible, because it's what people are familiar with.
No one really commented on the extended class aside from saying it's "awkward". Perhaps FriendList would have been a more appropriate class in that case if I really wanted to separate it out.
Thanks for all the answers :)
The routes you're talking about, and the way you're using subclasses to achieve this structure, seems a bit awkward to me. The standard convention of /controller/action/{id} works great for simple actions, but if you're creating a complex application you will always need to create custom routes. There are probably some good guidelines to use when creating these routes, but it really boils down to staying consistent across your application and keeping things as simple as possible.
I don't see any good reason to have /user/{id}/friends mapping to a "Friend" controller. Why not just have "friends" be an action on the User controller? Once you actually drill down to view a specific friend's page, you could use a Friend controller (/friends/view/123) or you could repurpose your User controller so that it works for a friend or the currently logged in user (/user/view/123).
Re: the bonus question, I'd stick with /photos/delete/{id} (/controller/action/{id}) as that's the most widely accepted mechanism.
I would prefer /photos/{id}/delete. My reasoning is that if you take one component off the end of an URL, it should still make sense.
It's pretty easy to assume what /photos/{id} should do: view the set of photos for that {id}.
But what should /photos/delete do? That's really unclear.
I know that there's kind of a default convention of /controller/action/id, but that organization is for the sake of mapping to the class/method architecture of controllers. I don't think it's a good idea to organize the UI to accommodate the code (the URL is in a way part of the UI).
Re comments: Yes, /photos/{id} maybe makes more sense to view a given photo by its id. /users/{id}/photos perhaps to view a collection. It's up to you.
The point is that you should think of the UI in terms of users, not in terms of code organization.
You can do either or. The problem is when you mix the two. /users/{id}/friends and /users/friends/{id} When someone has the id of "friends" this will fail. This may seem like a trivial case but it's very popular to use usernames for ids. You will have to limit user names for every action.
Sometimes you can't do /{controller}/{action}/{id}
I did a indie music site a while back and we did
/artist/{username}
/artist/{username}/albums
/artist/{username}/albums/{album}
We didn't want to test for conditionals so we didn't do
/artist/{username}/{album}
Since we didn't want to check for anyone with an album named "albums"
We could have done it
/artist/{username}
/artist/{username}/albums
/albums/{album}
but then we would lose the SEO advantage of having both the artist name and the album name in the URL. Also in this case we would be forcing album names to be unique which would be bad since it's common for artist to have album names the same as other artist.
You could do pure /{controller}/{action}/{id} but then you would lose some SEO and you can't do URL shortening.
/artist/view/{username}
/artist/albums/{username}
/album/view/{album}
Getting back to your example.
/users/{id}/friends/edit could work,
but it doesn't seem appropriate, since
you should never be editing someone
else's friend list.
In this case it should be /friends/edit since your user id is duplicate information assuming your in a session somehow. In general you want to support URL shortening not URL expansion.
(Bonus question)
Neither, i'd use REST. DELETE /photo?id={id}
It also depends on how you are storing your data. I could imagine in some cases you need a 'friend-list' to be a entity in your model. A logical approach would then be to specify a unique identifier for each friend-list, a primary key.
This would logically result in the following route, as you only need a primary key of the friend-list to edit or delete it...
/friends/edit/{friendListId}
It's up to you to decide. As pix0r stated: convention for small applications is /{controller}/{action}/{id} where {id} should be optional to match with most of your websites actions. In some cases applications get big and you want to define specific routes with more than 3 elements. In some cases certain entities just get a bigger meaning (above example) and you could decide to define a custom controller for it (which makes the default route perfect again...).
I'd stick with the default route /controller/action/id but just don't start making controllers for everything (like friends) in the beginning. The Model-View-Controller pattern makes it very easy for you to change routes later on, as long as all your route-links and actions (forms etc.) are generated based on routes and actions. So you don't really have to bother that much :)
The URLs themselves don't really matter too much. What is more important is what goes in each of your controllers. In your example you had your friend list extend the User class. If your list of friends is really just a list of users, maybe it should extend the Users controller so that you deal with lists of users in one place.
class Users {
public function index() {
$users = $this->findUsers();
}
protected function findUsers($userId=null) { ... }
}
class Friends extends Users {
public function index($userId) {
$users = $this->findUsers($userId);
}
}
If you have a hard time figuring out which class to extend write out what you need from each of the classes and pick the one with the longest list.

PHP MVC & SQL minus Model

I've been reading several articles on MVC and had a few questions I was hoping someone could possibly assist me in answering.
Firstly if MODEL is a representation of the data and a means in which to manipulate that data, then a Data Access Object (DAO) with a certain level of abstraction using a common interface should be sufficient for most task should it not?
To further elaborate on this point, say most of my development is done with MySQL as the underlying storage mechanism for my data, if I avoided vendor specific functions -- (i.e. UNIX_TIMESTAMP) -- in the construction of my SQL statements and used a abstract DB object that has a common interface moving between MySQL and maybe PostgreSQL, or MySQL and SQLite should be a simple process.
Here's what I'm getting at some task, are handled by a single CONTROLLER -- (i.e. UserRegistration) and rather that creating a MODEL for that task, I can get an instance of the db object -- (i.e. DB::getInstance()) -- then make the necessary db calls to INSERT a new user. Why with such a simple task would I create a new MODEL?
In some of the examples I've seen a MODEL is created, and within that MODEL there's a SELECT statement that fetches x number of orders from the order table and returns an array. Why do this, if in your CONTROLLER your creating another loop to iterate over that array and assign it to the VIEW; ex. 1?
ex. 1: foreach ($list as $order) { $this->view->set('order', $order); }
I guess one could modify the return so something like this is possibly; ex. 2.
ex. 2: while ($order = $this->model->getOrders(10)) { $this->view->set('order', $order); }
I guess my argument is that why create a model when you can simply make the necessary db calls from within your CONTROLLER, assuming your using a DB object with common interface to access your data, as I suspect most of websites are using. Yes I don't expect this is practical for all task, but again when most of what's being done is simple enough to not necessarily warrant a separate MODEL.
As it stands right now a user makes a request 'www.mysite.com/Controller/action/args1/args2', the front controller (I call it router) passes off to Controller (class) and within that controller a certain action (method) is called and from there the appropriate VIEW is created and then output.
So I guess you're wondering whether the added complexity of a model layer -on top- of a Database Access Object is the way you want to go. In my experience, simplicity trumps any other concern, so I would suggest that if you see a clear situation where it's simpler to completely go without a Model and have the data access occur in the equivalent of a controller, then you should go with that.
However, there are still other potential benefits to having an MVC separation:
No SQL at all in the controller: Maybe you decide to gather your data from a source other than a database (an array in the session? A mock object for testing? a file? just something else), or your database schema changes and you have to look for all the places that your code has to change, you could look through just the models.
Seperation of skillsets: Maybe someone on your team is great at complex SQL queries, but not great at dealing with the php side. Then the more separated the code is, the more people can play to their strengths (even more so when it comes to the html/css/javascript side of things).
Conceptual object that represents a block of data: As Steven said, there's a difference in the benefits you get from being database agnostic (so you can switch between mysql and postgresql if need be) and being schema agnostic (so you have an object full of data that fits together well, even if it came from different relational tables). When you have a model that represents a good block of data, you should be able to reuse that model in more than one place (e.g. a person model could be used in logins and when displaying a personnel list).
I certainly think that the ideals of separation of the tasks of MVC are very useful. But over time I've come to think that alternate styles, like keeping that MVC-like separation with a functional programming style, may be easier to deal with in php than a full blown OOP MVC system.
I found this great article that addressed most of my questions. In case anyone else had similar questions or is interested in reading this article. You can find it here http://blog.astrumfutura.com/archives/373-The-M-in-MVC-Why-Models-are-Misunderstood-and-Unappreciated.html.
The idea behind MVC is to have a clean separation between your logic. So your view is just your output, and your controller is a way of interacting with your models and using your models to get the necessary data to give to the necessary views. But all the work of actually getting data will go on your model.
If you think of your User model as an actual person and not a piece of data. If you want to know that persons name is it easier to call up a central office on the phone (the database) and request the name or to just ask the person, "what is your name?" That's one of the ideas behind the model. In a most simplistic way you can view your models as real living things and the methods you attach to them allow your controllers to ask those living things a series of questions (IE - can you view this page? are you logged in? what type of image are you? are you published? when were you last modified?). Your controller should be dumb and your model should be smart.
The other idea is to keep your SQL work in one central location, in this case your models. So that you don't have errant SQL floating around your controllers and (worst case scenario) your views.

Categories