dqkyz02602 2015-10-26 15:33
浏览 16
已采纳

MVC - 共同功能的地方?

I've just started to look into MVC and I'm pretty new. I would like to port procedural code across to it but I'm struggling (please no-one suggest to use a Framework).

I can understand how it works, but understanding is different to doing. In my procedural code, I have several functions such as message(). These are called if the user does not have permission to view the current page, for example.

My problem is adding this into MVC. I've added Twig so far and I've managed to render some Twig on the index page but using functions such as message before was as easy as this:

message('Message Text');

Adding it to the controller directory would allow it to be accessed as a web page, which I don't want. And through the model, I'm not sure how to do this without requiring the file first. I could use a function, but I don't want globals and this is partly why I'm changing.

How can I properly place commonly used functions?

Edit

What I'm using is a modified version of this: http://www.phpro.org/tutorials/Model-View-Controller-MVC.html

  • 写回答

1条回答 默认 最新

  • dongshao6591 2015-10-26 15:43
    关注

    I tend to think of traditional MVC like this:

    A controller is my business logic to implement my product.
    A model is the code to represent data.
    A view is what represents my product.

    Under this paradigm, what represents my product is what an end-user sees. So if it's a UX component, it's part of the view.

    In this way, it's pretty easy to figure out how to use it:

    1. You could use path/to/notifications.php and then $notifications = new Notifications(); where notifications.php is a class facilitating messages like you reference.
    2. You could extends Notifications on your view (or even a base view!) so that ANY view you instantiate immediately has access to your notifications class.
    3. You could (though probably shouldn't) require_once( 'path/to/notifications.php' ); and then the class or functions therein would be available. Again, you probably shouldn't do it this way

    The bottom line is this:

    • Place your old procedural code in a well organized class. It might be named something like Notifications if that's what the code does. The important thing is to organize well, name well, and do not try to force too much code into one thing.
    • Use that class in your code. You can explicitly use it's namespace and new an instance of it, or you can extend it to bring it along as the parent class of your view.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上