为什么 Rails 为每个请求都创建一个控制器? [英] Why does Rails create a controller for every request?

查看:19
本文介绍了为什么 Rails 为每个请求都创建一个控制器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从我之前的问题我了解到 Rails 会为每个请求创建一个控制器实例.

From my previous question I understood that Rails creates a controller instance for every request.

我的问题是,因为这个主题与我正在从事的项目的设计有关:

My question is, because this subject is related to the design of the project I'm working on:

为什么 Rails 会创建一个新的实例

Why does Rails creates a new instance of

class SomeController < ApplicationController; end

处理每个传入的请求?为什么不创建单例对象并将请求转发给这个对象?这似乎更有效,因为我们不会在为请求分配和清理对象上浪费资源?

to process every incoming request? Why not just create singleton object and forward requests to this one? This seems more efficient as we won't waste resources on allocating and cleaning objects for request?

推荐答案

实例化新控制器实例的开销是微不足道的,这意味着两个完全不相关的请求之间不会意外共享状态.处理器时间的任何节省"都将被产生破坏性错误的可能性所抵消.

The overhead of instantiating a new controller instance is insignificant, and it means there is no accidentally shared state between two completely unrelated requests. Any "savings" in processor time would be more than offset by the potential to produce devastating bugs.

请记住,控制器用于存储特定于请求的状态.重用控制器需要您在每个操作开始时重置您曾经设置的每个 @variable.否则,像 @is_admin = true 之类的东西可能会被设置并且永远不会被清除.您实际引入的不那么人为的错误会更加微妙,并且会消耗开发人员的时间.

Remember that controllers are for storing request-specific state. Reusing controllers would require you to reset every @variable you'd ever set, at the start of every action. Otherwise, something like @is_admin = true could wind-up being set and never cleared. The less contrived bugs you'd actually be introducing would be much more subtle and draining on developer time.

您看到了没有优化的地方.某些东西必须保持状态并在请求之间重置它,否则您会遇到意外共享状态的噩梦.如果您在请求之间持久化控制器实例,您只是将维护/重置状态的工作推到较低的级别,在那里答案可能仍然 实例化一些状态管理的新实例每个请求的类.计算机在分配和释放资源方面非常好,所以永远不要担心这一点,直到您真正知道这是一个瓶颈.在这种情况下,为每个请求实例化一个新控制器是正确的选择.

You're seeing optimizations where there are none. Something must maintain state and reset it between requests, or you have this nightmare of accidentally shared state. If you persist controller instances between requests, you're simply pushing the job of maintaining/resetting state down to some lower level, where the answer will likely still be to instantiate a fresh instance of some state-managing class for each request. Computers are very good at allocating and freeing resources, so never worry about that until you actually know it's a bottleneck. In this case, instantiating a new controller for each request is easily the correct choice.

在 Rails 的情况下,能够使用 @variable = value 从代码清晰度和可用性的角度来看是一个重大胜利,这或多或少需要丢弃每个实例请求完成时的控制器.

In the case of Rails, being able to use @variable = value is a major win from a code-clarity and usability stand-point, and this more or less necessitates discarding each instance of a controller when the request completes.

这篇关于为什么 Rails 为每个请求都创建一个控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆