且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么Rails为每个请求创建一个控制器?

更新时间:2023-09-28 17:13:22

实例化新控制器实例的开销并不重要,这意味着两个完全不相关的请求之间没有意外的共享状态。处理器时间中的任何节省都将被产生毁灭性错误的潜力所抵消。

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.