As far as I know, currently Yii 2 doesn't have an out of the box method to resolve ambiguity of controller and module names. An example of module hierarchy to describe what exactly I mean:
app\modules\v1\controllers\UserController // resolves the /v1/users and /v1/users/{id} actions
app\modules\v1\modules\user\Module.php // nested module, resolves the /v1/user/... controllers and their actions, e.g. /v1/user/something/{id}
In this case, the UserController conflicts with the user Module. The main reason of the ambiguity is the singular-plural magic of Yii 2 framework. I didn't find an appropriate solution to resolve this ambiguity. Further my ideas how to resolve it.
Rename the module.
Rename the UserController to the UsersController.
Create an additional submodule, and place there the UserController. E.g. app\modules\v1\modules\root\controllers\UserController
I'm not sure that at least one of these options is a quite elegant one and a proper solution in view of the Yii 2 philosophy.
Coming back to the main question, what is a more appropriate approach to resolve this issue by the Yii 2 philosophy? Controller and Module is two different types of objects, which is differently pluralized or not, thus should be right way to separate them in the routing for the described case.
How I usually deal with this depends a bit on how I'm structuring things.
Let's say I have users, departments, orders and maybe some other stuff. All these concepts have their own module in which all interactions take place. If I want to create REST controllers for all these concepts I can choose to add a controller to every module or I can create a dedicated API module for the controllers.
When creating a dedicated module for this purpose I usually name it api, maybe with some nested versioning module(s) inside. So in this situation I would get the following structure app\modules\api\controllers\UserController which would result in the URL /api/user. No ambiguity there and pretty clear what this is meant for.
When adding such a controller to the module itself I choose a better name than just 'UserController'. When asking myself the question 'What does this controller accomplish?/What does it do?' I find that just UserController doesn't cut it; Especially when inside a User module, resulting in /user/user. This controller is probably going to exist alongside one or more different controllers in the User module, all meant for something different. So, usually, I end up naming it just ApiController, resulting in /user/api. Another controller could be the ProfileController. So when looking at the URLs it's pretty clear what /user/api and /user/profile do. Without the ambiguity.
I am not sure I can fully understand the question, but probably you're asking about classname aliases?
use My\Full\Classname as Another;
Related
I'm trying to understand the MVC pattern in Phalcon.
In my current application I only need ONE template file for each table. The template contains the datagrid, the SQL statement for the SELECT, the form, add/edit/delete-buttons, a search box and all things necessary to interact with the database, like connection information (of course using includes as much as possible to prevent duplicate code). (I wrote my own complex framework, which converts xml-templates into a complete HTML-page, including all generated Javascript-code and CSS, without any PHP needed for the business logic. Instead of having specific PHP classes for each table in the database, I only use standard operation-scripts and database-classes that can do everything). I'm trying to comply more with web standards though, so I'm investigating alternatives.
I tried the INVO example of Phalcon and noticed that the Companies-page needs a Companies model, a CompaniesController, a CompaniesForm and 4 different views. To me, compared to my single file template now, having so many different files is too confusing.
I agree that separating the presentation from the business logic makes sense, but I can't really understand why the model and controller need to be in separate classes. This only seems to make things more complicated. And it seems many people already are having trouble deciding what should be in the model and what should be in the controller anyway. For example validation sometimes is put in the model if it requires business logic, but otherwise in the controller, which seems quite complex.
I work in a small team only, so 'separation of concerns' (apart from the presentation and business logic) is not really the most important thing for us.
If I decide not to use separate model and controller classes,
what problems could I expect?
Phalcon's Phalcon\Mvc\Model class, which your models are supposed to extend, is designed to provide an object-oriented way of interacting with the database. For example, if your table is Shopping_Cart then you'd name your class ShoppingCart. If your table has a column "id" then you'd define a property in your class public $id;.
Phalcon also gives you methods like initialize() and beforeValidationOnCreate(). I will admit these methods can be very confusing regarding how they work and when they're ran and why you'd ever want to call it in the first place.
The initialize() is quite self-explanatory and is called whenever your class is initiated. Here you can do things like setSource if your table is named differently than your class or call methods like belongsTo and hasMany to define its relationship with other tables.
Relationship are useful since it makes it easy to do something like search for a product in a user's cart, then using the id, you'd get a reference to the Accounts table and finally grab the username of the seller of the item in the buyer's cart.
I mean, sure, you could do separate queries for this kind of stuff, but if you define the table relationships in the very beginning, why not?
In terms of what's the point of defining a dedicated model for each table in the database, you can define your own custom methods for managing the model. For example you might want to define a public function updateItemsInCart($productId,$quantity) method in your ShoppingCart class. Then the idea is whenever you need to interact with the ShoppingCart, you simply call this method and let the Model worry about the business logic. This is instead of writing some complex update query which would also work.
Yes, you can put this kind of stuff in your controller. But there's also a DRY (Don't Repeat Yourself) principle. The purpose of MVC is separation of concerns. So why follow MVC in the first place if you don't want a dedicated Models section? Well, perhaps you don't need one. Not every application requires a model. For example this code doesn't use any: https://github.com/phalcon/blog
Personally, after using Phalcon's Model structure for a while, I've started disliking their 1-tier approach to Models. I prefer multi-tier models more in the direction of entities, services, and repositories. You can find such code over here:
https://github.com/phalcon/mvc/tree/master/multiple-service-layer-model/apps/models
But such can become overkill very quickly and hard to manage due to using too much abstraction. A solution somewhere between the two is usually feasible.
But honestly, there's nothing wrong with using Phalcon's built-in database adapter for your queries. If you come across a query very difficult to write, nobody said that every one of your models needs to extend Phalcon\Mvc\Model. It's still perfectly sound logic to write something like:
$pdo = \Phalcon\DI::getDefault()->getDb()->prepare($sql);
foreach($params as $key => &$val)
{
$pdo->bindParam($key,$val);
}
$pdo->setFetchMode(PDO::FETCH_OBJ);
$pdo->execute();
$results=$pdo->fetchAll();
The models are very flexible, there's no "best" way to arrange them. The "whatever works" approach is fine. As well as the "I want my models to have a method for each operation I could possibly ever want".
I will admit that the invo and vokuro half-functional examples (built for demo purposes only) aren't so great for picking up good model designing habits. I'd advise finding a piece of software which is actually used in a serious manner, like the code for the forums: https://github.com/phalcon/forum/tree/master/app/models
Phalcon is still rather new of a framework to find good role models out there.
As you mention, regarding having all the models in one file, this is perfectly fine. Do note, as mentioned before, using setSource within initialize, you can name your classes differently than the table they're working on. You can also take advantage of namespaces and have the classes match the table names. You can take this a step further and create a single class for creating all your tables dynamically using setSource. That's assuming you want to use Phalcon's database adapter. There's nothing wrong with writing your own code on top of PDO or using another framework's database adapter out there.
As you say, separation of concerns isn't so important to you on a small team, so you can get away without a models directory. If it's any help, you could use something like what I wrote for your database adapter: http://pastie.org/10631358
then you'd toss that in your app/library directory. Load the component in your config like so:
$di->set('easySQL', function(){
return new EasySQL();
});
Then in your Basemodel you'd put:
public function easyQuery($sql,$params=array())
{
return $this->di->getEasySQL()->prepare($sql,$params)->execute()->fetchAll();
}
Finally, from a model, you can do something as simple as:
$this->easyQuery($sqlString,array(':id'=>$id));
Or define the function globally so your controllers can also use it, etc.
There's other ways to do it. Hopefully my "EasySQL" component brings you closer to your goal. Depending on your needs, maybe my "EasySQL" component is just the long way of writing:
$query = new \Phalcon\Mvc\Model\Query($sql, $di);
$matches=$query->execute($params);
If not, perhaps you're looking for something more in the direction of
$matches=MyModel::query()->where(...)->orderBy(...)->limit(...)->execute();
Which is perfectly fine.
Model, View and Controller were designed to separate each process.
Not just Phalcon uses this kind of approach, almost PHP Frameworks today uses that approach.
The Model should be the place where you're saving or updating things, it should not rely on other components but the database table itself (ONLY!), and you're just passing some boolean(if CRUD is done) or a database record query.
You could do that using your Controller, however if you'll be creating multiple controllers and you're doing the same process, it is much better to use 1 function from your model to call and to pass-in your data.
Also, Controllers supposed to be the script in the middle, it should be the one to dispatch every request, when saving records, when you need to use Model, if you need things to queue, you need to call some events, and lastly to respond using json response or showing your template adapter (volt).
We've shorten the word M-V-C, but in reality, we're processing these:
HTTP Request -> Services Loaded (including error handlers) -> The Router -> (Route Parser) -> (Dispatch to specified Controller) -> The Controller -> (Respond using JSON or Template Adapter | Call a Model | Call ACL | Call Event | Queue | API Request | etc....) -> end.
I'm currently using Symfony2 and and I'm trying to divide my code into different controller (like an Ajax Controller, a User Controller etc...) but I don't really know when I should use a create a new One.
For example my DefaultController is starting to be quite big (~800 lines) and I was wondering if having a too long controller could impact the website's performance? (Longer loading time...)
And, if it does, when should I split the controller into smaller ones ?
I would say that you should group your actions by which operate on the same data (entities) or operate within a well defined responsibility. E.g. UserController for users, PostController for blog posts, etc. This means that if you want to create an action which role is different than the rest of the actions, put it in a separate controller.
Symfony is caching almost everything so I don't think that huge controllers would cause an impact to the perfomance but if you have a thousands lines long controller, I'm not sure that it does only one thing.
The controller's size can be a warning sign too for the misplaced queries and business logic. You should separate QueryBuilder calls into Repository classes and other logic to services and event handlers. You can save more lines by using annotations instead of PHP code.
I think it's a good idea to start with a controller for each relevant model, with a CRUD structure.
Of course it depends on your needs, but if you have a model "Post", you probably will need a PostController with CRUD routes and methods, like : index (/posts), new, update, create, delete...
Depending what you need you can delete or add some method relative to a
Post from this base structure.
Try to detect what is realy relative to a specific model in your defaultController and create a controller for it.
Good luck.
What #riska and #Yoann said all holds true.
In addition, I prefer not to create separate controller if I'm sure that it hold only that one method. In that case, I just put it into DefaultController.
From my experience, controllers are the part of UI layer. If you care a lot about keeping your controllers small, let me give you the best scenario you can make what a controller must do:
1.Call the appropriate service
2.Return the response
That is 2 lines of code for each controller action, or you can even make it in one line.
Like person above said, controllers are usually separated by what type of entities / services they operate on. If you for example have an entity - lets say User, the following actions are most likely to be in there: createAction, editAction, removeAction, registerAction, activateAction, loginAction, logoutAction and so on...
It does not have any impact on performance if your controllers are thin or fat. The code will be executed in the similar flow, and all classes are being cached in the production environment.
What I have is the following db structure(tables):
lists[name,id]
list_items[title,list_id,content]
I've created the needed files and code(the MVC) needed to manage the first table(lists).
I also added the hasMany to the model class. At that point I am stuck.
What I need is a solution for managing each item (basic CRUD, I assume that complex management is just an advanced CRUD that I will find out how to do by myself).
I will be specific: since it's a content that have no place (but the admin) that it will be used by itself, should I -
create a full mvc structure for it? (can or should I implement it somehow[how?] in the lists package?
if not, how can I attach the tables? (since the use is about to be dropped in version 2)
would an element(cake concept/context) will be the appropriate way to create a view for such situation?
ANY insight will be appreciated.
If I undertant correctly, you want to create a CRUD part of this tables by yourself, without bake.
You need to write all the MVC estrucure and be carefull with the naming combention of cakephp http://cakebaker.42dh.com/2006/02/18/cakephp-conventions/
You need the model into app/models and also a a controller into app/controllers (remember naming combentions) and for each model you need a folder into /app/views.
Alfo, every, every function in your controller needs a view, even if this action doesn´t write anything to screen
I hope this was usefull.
Have you tried using Cake's bake feature? Your CRUD will be automatically created in about 2 seconds. I would also recommend you do the Blog tutorial to get a feel for scaffolding.
CakePHP is all about convention over configuration. Eg naming conventions for tables, controllers, models etc.. So much can be done automagically.
Ok, it's my fault. I've never ever learned programming at a school and that's why i'm always ending up in a spaghetti code. I've always curious about different patterns and tried to understand them at least in a basic level.
MVC is my worst fear and i think i'll be never able to use it's advantages because of i don't understand it's fundamentals.
My actual question/problem looks like:
The front controller calls a 'Core' class which is doing some initialization then it calls the actual controller with the correct action/parameters. The controllers always extending the 'Core' class so i can acces it's variables, etc. They're working nicely together but here comes my real problem.
Some kind of methods (getting a database entry in most of the cases) are required in different cases. (e.g. a product needs it's manufacturer)
In this scenario i have two (bad) choices:
Inject the required method into the 'Core' class so it's getting bloated over time
Inject the required method into the actually called controller so i will end up a redundant codebase
I see a lot of possible problems in my approach:
Controllers are always extending 'Core' class
'Core' controller holds the database object so without it i cannot access my Db
Database functions (e.g. getting a product) are in the controllers but i cannot access them because they're always calling 'Core' first (extending problem again)
Please tell me:
Where is the biggest problem in my approach and where can i correct it?
Note:
Please don't treat this as a general question, i think this is an answerable thing. If you need some clarification, please ask for it and i'll try to lighten up things.
Thanks for your precious time, fabrik
Your data is represented to your Controller and View through the Model. The Model may be supported by a Repository but depending on the overhead you might want to provide your database access in your Model. The data architecture should be similar to this:
(Repository<===>)Model<===>Controller--->View
Your biggest problem is having the "Core" class, get rid of it asap.
By the way, the FrontController is not the only way to do things MVC things either.
Your second problem is that controller deals with database, it shouldn't. I suggest you use some abstract data layer, which you use only in your models. And controller should deal only with models, it shouldn't care how models get their data persisted and fetched.
Look into using a DI framework to automatically inject an instance of a repository into your controllers (or even better, a proxy class). Try to keep business logic outside of your controllers, but rather, refector it out into a helper or proxy class.
I tend to split my logic up into views => controllers (just for interaction between business later and view) => business logic => models (DTOs) => low-level data access at a minimum.
Also, if you need common helper functionality in your views, perhaps create several extensions to help.
When using the MVC pattern, which I'm not terribly experienced with, I find myself naming things like this:
/app/views/widget.php
/app/models/widget.php
/app/controllers/widget.php
That appeals to me because it's easy to find associated classes, and I lean towards shorter names when practical. However, when I'm looking in my IDE, I see three different files called widget.php, which is confusing. I'm tempted to add "_v", "_c", "_m" or something to each name. How do you handle this?
FWIW, I'm using CodeIgniter at the moment, and I don't know if there are any special benefits to using a particular convention, or any standard practices. Regardless, I'm intersted in the best-practices from various platforms.
My view ends in phtml, so that would make Widget.phtml. My model is a Widget so that would yield Widget.php, just like that, and my controller would be WidgetController.php.
I personally think that having everything named widget.php gets confusing even if the files are in separate files. I tend to append either Model, View, or Controller to the end of the files names in addition to having the files divided into respective folders. While it is more verbose it is much more expressive and easier for newcomers to your code base to follow your code. So my widget (in Java which is what I most frequently use for mvc) would be named as follows:
/app/widget/view/WidgetView.jsp
/app/widget/model/WidgetModel.java
/app/widget/controller/WidgetController.java
/app/coolwidget/view/CoolWidget.java
...
Plus when I'm in an IDE or editor I tend to look at the file name and not the full path to the file when editing. So if I'm editing the Model, View, and Controller for my widget, I don't want to be examining the file paths to figure out which one I'm working on.
CodeIgniter (and for that matter any framework) relies on a set of 'conventions' (rules basically). One of those rules is how routing is handled. For example, the 'widget' file you have in /app/controllers/ will translate to a URL of http://yoursite.com/widget/action/ (where action are function names in your Widget class.
The normal convention is to use CamelCaseNaming for your classes and lowerCamelCase naming for methods. Each framework has a different routing engine. If you have class WidgetBlahBlah will translate to a url of /widget-blah-blah/ or /widget.blah.blah/ (depending). Action names and routing are similar.
As for naming of views, views should be named the same as your actions. They should be organized into sub directories based on your class names. Again, this is all convention. Actions in your classes look for views in specific locations named a specific name.
If you're going to use MVC I would suggest going back to the beginning and learning how to use it. MVC is designed to be rapid development by understanding a set of conventions and leveraging them. Maybe start here: http://codeigniter.com/user_guide/toc.html
I generally just leave them named without any special convention, and distinguish between the different files by looking at:
- folder names
- file contents
With syntax highlighting, a view file containing mostly html is very easy to distinguish from a controller or model. As for telling the difference between models and controllers: I don't generally name models and controllers with the same names, so there isn't a problem there for me.