doutui6241 2015-11-13 19:52
浏览 92
已采纳

我应该在哪里将价格计算逻辑放在Laravel中? [关闭]

In this question I am asking for "best practice" advice for Laravel.
I am working on an "airbnb-like" website where I list accommodations. On various pages in the site (backend and frontend) I need to calculate the price for the accommodations. The price is calculated by combining the accommodation object with the search query.

Eg.
-accommodation: rate = 50 euro per night
-search query: 4 nights
-> result: total price = 200 euro

Where should I put the logic that makes these price calculation?
For example:
-Should I create a PricesController for this?
-Should I add functions/methods to the AccommodationsController that calculate this, or to the Accommodation model?
-Should I create a ServiceProvider for this?

  • 写回答

3条回答 默认 最新

  • dowe98261 2015-11-13 21:02
    关注

    There's no defined way to pull this off, which in my opinion is the greatest thing about laravel.

    Maybe create a directory named Calculations in app/ (app/Caclulations/Accommodation.php), and namespace it as such? It would be an nice object oriented approach to this problem.

    namespace App\Calculations;
    
    class Accommodation
    {
        /**
         * The rate per night.
         *
         * @var float
         */
        protected $rate;
    
        /**
         * The amount of nights for the stay.
         *
         * @var int
         */
        protected $nights = 1;
    
        /**
         * Constructor.
         *
         * @param float $rate
         * @param int   $nights
         */
        public function __construct($rate = 50.00, $nights = 1)
        {
            $this->rate = $rate;
            $this->nights = $nights;
        }
    
        /**
         * Calculates the accommodation and returns the result.
         *
         * @return float
         */
        public function calculate()
        {
            return $this->rate * $this->nights;
        }
    }
    

    This way you can modify the calculation class if the calculation changes, extend it from other calculations (such as a base calculation), and maybe insert some other useful things in the class such as currency type.

    Usage:

    $total = (new Accommodation($rate, $nights))->calculate();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 关于多单片机模块化的一些问题
  • ¥30 seata使用出现报错,其他服务找不到seata
  • ¥35 引用csv数据文件(4列1800行),通过高斯-赛德尔法拟合曲线,在选取(每五十点取1点)数据,求该数据点的曲率中心。
  • ¥20 程序只发送0X01,串口助手显示不正确,配置看了没有问题115200-8-1-no,如何解决?
  • ¥15 Google speech command 数据集获取
  • ¥15 vue3+element-plus页面崩溃
  • ¥15 像这种代码要怎么跑起来?
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection