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条)

报告相同问题?

悬赏问题

  • ¥15 用verilog实现tanh函数和softplus函数
  • ¥15 求京东批量付款能替代天诚
  • ¥15 slaris 系统断电后,重新开机后一直自动重启
  • ¥15 51寻迹小车定点寻迹
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题