I have a Backend in Laravel, which is basically a REST API, because I'm using AngularJS in the FronEnd and making ajax requests.
Let's say I have to make a simply CRUD for Users
And I don't know if there is any difference between putting some of the parameters in the Route itself or all of them in the Form Input.
For Example:
Route::post('/Users/Update', 'UsersController#update);
And then call the 'id' parameter from:
Input::get('id')
or
Route::post('/Users/Update/:id', 'UsersController#update);
and include it as a parameter of the function update like:
public function update($id) { }
Is there any real difference between this two ways? maybe security issues? coding standards? or is it the same?
Should I just use Laravel's REST controllers?
If you are building a REST API you should have a URL like example.com/posts/42 and not example.com/posts?id=42 because it is cleaner and it is a coding standard.
I would also drop uppercase characters in your URLs and definitely go for your second choice of implementation. By the way, if you need to update a user you should use a PUT request like so: PUT users/:id.
The concise some-what opinionated answer:
You should define your route as:
Route::put('/users/:userId', 'UsersController#putUser');
Your public function putUser($userId) {} should return a 204 No Content on success.
The reasoning:
I've changed the route to be a PUT request to closer follow REST principles. Changing the controller method to putUser from update allows us to better define what the method is intending to do. While it seems trivial, it will help you distinguish between a PUT and PATCH update if you ever decide to implement one in the future. I used PUT as the method here but you can read about PATCH vs PUT and decide how far you want to go into following REST principles.
As for laravels restful controllers I feel they impose restrictions and add no real benefit so for REST api's I don't recommend using them.
Related
Well i'm learning Symfony (3.3) and i'm little confused about Service Container. In first tutorial the lector show register, login, add post, edit, delete methods in User, Article Controllers. Then in other tutorial, they show same methods but use Service Container (User and Article services) with User and Article interfaces. So .. what is the best practice for implementation in Services instead of Controllers.
I would like to add to Alexandre's answer that it is considered best practice to keep your controller 'thin'. In other words, only put code in your controller that really has to be there (or if it only makes sense to put it in your controller).
Services are like tools you can use in your application. A service in an object that helps you do something. In one service, you can have many functions. I think the best way to understand the difference is that a controller is for one specific action, a service can be used in many actions. So if you have parts of code that you want to use in more than one controller, create a service for it. And for the sake of re-usability, create functions in your service that do only one thing. This makes it easier along the way to use these functions.
the "best practise" depends on what you want to do with the Service. If you build an REST-Api you might want to do Database-Operations in Controller. Why? When you rely on the SOLID-Pattern you want to reduce or eliminate redundant code. If you code a real REST Api you don't have redundant code because each REST-Verb will do a different query/thing.
So in a non-REST-Api-application you will have a lot of redundant code. You do the same things/services on different pages/controller-actions. So the best thing is to implement all the business-logic in services to have it only one time in one place. If you have a lot of individual queries place them into repositories. If you have business-logic that fit's into an entity-class place them there. So in my opinion you can choose a thick controller/no service design in API's and a thin controller/thick service design in classic symfony front-/backend applications.
But one more thing: there is no totally wrong way to design an application. But if you work with other people or want to run the application longer than a month (without having trouble to maintain it) you should pick a common design-pattern.
Controller must implement the application logic like check if it's a post request or if a form is submit etc...
Never use DQL or any SQL Request directly inside a controller !
EDIT In the example i use a find method inside the controller because it's a Repository method but i parse the result inside slugify (my service method)
Services contains business logic like formatting phone numbers, parse some data etc...
Of course you can inject a repository inside a service and call your methods inside it.
An example:
//This is a fictive example
public function indexAction(Request $request) {
//Application logic
if(!$request->get('id')) {
//redirect somewhere by example
}
$article = $this->getDoctrine()
->getRepository(Article::class)
->find($request->get('id'));
//Business Logic
$slug = $this->get('my.acme.service')->slugify($article->getTitle());
}
Hope this helps
I have been used laravel, and I find it's by far the best PHP Framework there is. But even so, I still think that to be able to understand it and PHP MVC's in general, I need to make my own first.
So, as of now, I'm in the process of making my own MVC, I got most things covered. But I wanted to add a feature that is identical to Laravel, which is the Post-Redirect-Get feature, (or so I think).
What I mean is, for those unaware, that if a person visits a link, say localhost/project/laravel/public/profile using the Route::get('localhost/project/laravel/public/profile', 'SomeController#action) He will only be able to view the profile page, from the action() function in SomeController. But when he uses the Route::post('localhost/project/laravel/public/profile', 'SomeController#action2), only when does is the POST request sent from the localhost/project/laravel/public/profile URL, will the action2() function activate.
So, My question is,
How can I make my own Route::get() and Route::post() to work like in laravel
If you want have get and post in the same route you should try this methods
POST and GET in the same pattern
In modern web frameworks (Laravel, Symfony, Silex, to name a few), there seems to be a pattern of using a routes.php file or similar to attach URIs to controllers. Laravel makes it a bit easier with an option to use PHP annotations.
But to me all this feels like a bit of a code repetition, and when you are creating/modifying controller logic, you have to keep routes file always at hand. Interestingly, there's a simpler way I saw in several old frameworks, and I used to use this in my old projects as well:
Controller. All classes in src/controllers folder (old way) or all classes in YourApp\Controllers namespace are being automatically mapped to the first part of the URL by adding "Controller" to it. Example: /auth gets mapped to AuthController, /product/... — to ProductController, and / — to default IndexController.
Action. Action is the second part of the URL, and it gets mapped to the method name. So, /auth/login will call AuthController::loginAction() method. If no second part provided, we try indexAction(). Don't want people to access some internal method? Don't make it public.
Parameters. Next parts of the URL are being mapped to the arguments of the method; if there are Application and/or Request type hintings in the argument list, they are skipped so they can be properly injected; we can access GET/POST variables as usual through Request.
Here's the full example, using all these features together:
URL: https://example.com/shop/category/computers?country=US&sort=brand
namespace MyApp\Controllers;
class ShopController extends BaseController {
public function categoryAction(Application $app, Request $req, $category, $subcategory = null) {
echo $category; // computers
echo $subcategory; // null, it's optional here
echo $req->get('country'); // US
echo $req->get('sort'); // brand
}
}
I'm sure it seems to lack some familiar features at first, but all features that I can think of could be easily added if needed — using attachable providers, connecting middlewares, branching controllers to subcontrollers, specifying HTTP methods, and even performing a bit of a pre-validation on the arguments. It's very flexible.
This approach would really speed up the routing creation and management. So besides having all the routes in one file (which is also not always true, considering various providers, using ->mount() in Silex or bundles in Symfony), what are the reasons modern frameworks seem to prefer this way of doing MVC routing over the simpler way I've described? What am I missing?
I'll speak here from Symfony/Silex perspective:
Decoupling. routes.php provide separation of URL mapping and controllers. Do you need to add or change URL? You go straight to routes.php. Very handy if you want to change a lot of them.
Flexibility. Generally, routes.php is a bit more flexible approach. SEO might go crazy and might require you to have route like /shop_{shopName}/{categoryName}/someStaticKeyword/{anotherVar}. With routes.php you can easily map this to your code, but this might become a problem if your routes are directly mapped to the code. Even more, you can have this only controller, you don't need to write controllers for each slash part. You can even have different controllers handling the same URL with different variable parts, for example /blog/[\d]+ or /blog/[a-z-]+ being handled by different controllers (one might generate redirect to another). You might never need to do something like this, but this is just a demonstration of flexibility of this approach - with it anything is possible.
Validation. Another thing to consider is that routes.php provide simple means of validation via ->assert method. That is, routes.php does not only map URLs to controller methods, but also ensure that these URLs match specific requirements, and you don't have to do this in code (which in most scenarios would take a bit more code to write). Also, you can create default asserts for some variables, for instance, you may ensure that {page} or {userId} are always \d+, single line in routes.php that would take care of all usages of {page} or {userId}.
URL Generation. One more feature of routes.php is url generation. You can assign any route any name (via ->bind() method) and then generate URLs based on that name, and providing variables for parts of URL that change. And once we have this system and use URL generator throughout our code we can change URLs as much as we want, but we won't have any need to edit anything but routes.php. And once again - these are flexible names, that you won't have to change everywhere throughout your project once URL has changed and you are not limited choosing the name. It might be much shorter than the URL, or a bit more verbose.
Maintainability. Say, you might want to change some urls (as in example above - from /blog/[\d+] to /blog/[a-z-]+. Also, you might want to keep both of them for some time, and make old one redirect to the new one). With routes.php you simply add a new line and add a todo memo to remove it in some time if you want to remove it later.
Sure, all of this might be achieved with any aproach. But would that be this simple, flexible, transparent and compact as this approach?
Just as note, the standard edition of Symfony is shipped with SensioFrameworkExtraBundle, that allows to use annotations instead of file-based declaration:
/**
* #Route("/")
*/
public function indexAction()
{
// ...
}
In the same manner, you can set the prefix for the whole controller file:
/**
* #Route("/blog")
*/
class PostController extends Controller
{
/**
* #Route("/{id}")
*/
public function showAction($id)
{
}
}
Still, we have to declare it. I think the main reason is that routing requirements are heavily influenced by SEO optimizations. For anything that faces the public you want some keyword-rich URL. The "public" logic organization may also be different, you may have only one controller to deliver all your static pages, still you want those to be /contact, /about...
In some domains, routes can be inferred with conventions. If you create a REST API using FosRestBundle, it will auto-generate routes based on your controllers/actions names on the ressource approach. In general I think the FosRestBundle got a lot of things in their approach, you can easily parse and validate query parameters at the same time:
class FooController extends Controller
{
/**
* This action route will be /foo/articles, GET method only
*
* #QueryParam(name="val", default="75 %%")
*/
public function getArticlesAction(ParamFetcher $paramFetcher)
{
...
}
I always prefer having the routes in a config file rather than using annotations because, firstly, I feel it's more maintainable and easier to have an oversight. It's easier to ensure that you don't have any conflicting routes when you can see them all together.
Additionally, it's theoretically faster. Annotations require reflection, where the application needs to scan the file system and parse each controller to collect the set of routes.
The reason is probably maintainability for the long term. It doesn't matter how the routes are set up but generally, Laravel as a framework focuses on the simplicity and the small things that make the framework great. As long as it is easy to use for the user (web developer in this case), the goal is reached.
You can use a different name for the routes.php file and also use multiple route files, if you have a lot of routes in your application.
You can try and rethink the whole concept to improve it but I don't think that Laravel's routes need really a big change to make it even easier. It's already simple. Maybe it will be changed for the better in the future but for now, I think it's fine.
I'm adding an API to a Symfony-application which should act as a REST web-service. But there are a few open issues.
Different URIs for bots?
I often read the "suggestion" to use URIs like /api/:id/[...], but I think they wouldn't be REST-compliant: No matter whether bot or human - the same unique resource is identified.
I'm asking, since my statement above makes sense, but I don't expect all the others to be at fault.
Modifying existing controllers?
There are several reasons why I need a separate controller-logic for both cases:
No session-login in the case of a api-requests
different Symfony-forms have to be created (For instance, no widgets are required, at all.)
JSON / XML instead of HTML output
I don't want to modify existing controllers. According to the Open-Closed Principle, classes should be open for extension but closed for modifications, and the controller classes are already in use in a "production"-environment.
My idea is to use an extra HTTP header-field (e.g. "X-UseApi"). The routing should call different actions by evaluating it. Is this possible inside routing.yml? How? Do you have other ideas?
Authentication
This is how I implemented bot-authentication:
$user = Doctrine_Core::getTable('sfGuardUser')->findOneByUsername($params['user']);
if($user->checkPassword($params['password']))
{
//...
}
But the code looks like a workaround to my eyes. Are there better solutions for the whole REST authentication issue? Is the sfGuardPlugin / sfDoctrineGuardPlugin not meeting conditions for such use cases?
Thanks in advance and cheers,
fishbone
my way of doing this would be to use sf_format in routes to distinguish between robot and human (robot will probably need to consume XML whereas human will want HTML.
I would alter my controllers in a way that I would delegate the logic to separate classes depending on what format is requested (this shouldn't be too much work and you would get the flexibility you need).
As for authentication - please provide a bit more information on how do you do it now - the example isn't enough for me to get the general idea of how your implementation works.
Different URIs for bots?
I suggest to not worry too much about URIs. There are more problems with them and thinking too much about it just results in losing time. IMHO it would be great if there would be standardized conventions how to define RESTful URIs. Here is an article about it: http://redrata.com/restful-uri-design/ . You can see that every way of designing your uris has its pros and cons.
But today I would reject the statement that 'api/...' isn't REST compliant. I would just avoid it.
Controller and authentication
Finally, my solution was to implement some sfFilters with responsibilities as follows:
ApiAccessFilter: sets request-attribute 'isApiRequest' if X-ApiKey is defined as header field.
ApiKeyAuthFilter: identifies a user by X-ApiKey, calls signIn / forwards to login-action.
SecureApiAccessFilter: Checks whether the current user has credential
'apiWriteAccess', if HTTP-method is POST, PUT or DELETE.
The first filter allows me to call $request->getAttribute('isApiRequest') later in my actions. That's similar to isXmlHttpRequest(). Finally I came to the conclusion that I have to modify existing actions, because requirements have changed due to the web-service extension.
Cheers, fishbone
I am learning the PHP MVC pattern for my backend implementation. Looking at this excellent example:
Implementing MVC in PHP: The Controller
http://onlamp.com/pub/a/php/2005/11/03/mvc_controller.html
I feel comfortable with the execution flow in a GET.
But there is no mentioning of what happens in a POST. What would the typical controller code for the POST do? I wonder if I am misunderstanding something obvious here, since I can't find similar situations in previous SO posts or Google.
For example: An app to manage persons,(name, last, age) wants to add a record to db when a POST hits the controller.
What happens next?
My guess is that the 'View' is not used at all, or maybe for confirmation?
Is there just a call from the controller to a model class that adds a record to db?
Or do I skip the controller altogether for a POST and go directly to an "add record" script?
Is there any available example?
Thanks in advance,
Ari
Well, POST is basically the same as GET, just some random chunks of info client sended to server. So you can treat it the same way.
I worked with CodeIgniter MVC framework in PHP. It uses GET URI to route to controller and it's methods. When the POST request comes, it treats its URI in the same way. The later actions are in the hand of the programmer, who accesses POST request data directly or through some wrapper, and he can also don't use it at all.
I need to say that you focus on the wrong parts. MVC is not the model of everything, and it doesn't say how to treat POST or GET requests. It's just a simple principle known many years before the name "MVC" became famous as the principle about splitting of logic, data and representation. And most of software(from old to new) actually do this splitting, because it is very hard not to do this in most cases. In some apps the borders are not so evident, some of them even haven't object model. The implementation of the app is always up to you, because MVC doesn't say you what to write but just gives some clues about highest level organization of you code.
P.S. Sorry for my bad English.
Typically, the controller would process the request (the controller processes ALL requests), then call into the model to actually manipulate data based on the request, and then either redirect to somewhere else (triggering a new GET request), or invoke a view to output a resulting page.
Well, if you are going to build your own MVC pattern solution, you could make one tricky thing. Since you're handling MVC you're supposed to have a really reliable routing manager. So after parsing your URL and defining what controller/method you are supposed to trigger, you could make something like:
<?php
...;
$method_name = (count($_POST) > 0) ? "post_".$route_result : $route_result;
...;
and later in your controller class you could do something like:
<?php
namespace Controllers;
class MyController extends \System\Controller {
function my_method($whatever = null){
...;
return $this->view($model_or_whatever); // supposed that you prepared view Class in routes
}
function post_my_method($whatever = null){
...;
return $this->view($model_or_whatever); // supposed that you prepared view Class in routes
}
}