【问题标题】:Accept two different model instances as a function argument php接受两个不同的模型实例作为函数参数 php
【发布时间】:2019-06-07 14:55:43
【问题描述】:

我正在编写一个辅助函数,通过检查是否有任何相关字段不等于 null 来检查我的数据库中是否存在任何地址信息。

所以,我需要在函数中接受两个模型作为参数。

  • 应用\客户
  • 应用\供应商

传递的变量可以是任意一个。

对于应该只接受一种模型的函数,我可以这样做:

function check_for_address_info(App\Customer $customer) {
    // other unrelated stuff
}

有没有办法接受这两种模型,或者我必须通过执行以下操作在函数中手动检查它:

function check_for_address_info($param) {
  if(!is_a($param, 'App\Customer' || !is_a($param, 'App\Supplier')) {
    // not an instance of either model
    return false;
  }

  // do stuff as normal
}

关于如何接受两个不同的模型作为函数参数的任何想法?

我在 Laravel 5.8 上。

【问题讨论】:

    标签: php laravel laravel-5 laravel-5.8


    【解决方案1】:

    有两种方法,如果继承有意义,您可以扩展父模型并将其声明为参数的类型。这将在运行时进行检查,如果您将错误的类型传递给方法,则会提供错误。

    public class Profile extends Model {
    }
    
    public class Customer extends Profile {
    }
    
    public class Supplier extends Profile {
    }
    
    function check_for_address_info(App\Profile $customerOrSupplier) {
    }
    

    在弱类型语言中,具有泛型参数是很常见的。 PHP 解决这个问题的方法是你可以在PHP Doc 块中声明它。这不会在运行时检查类型,主要用于类型提示、文档和静态分析工具。

    /**
     * @parameter \App\Customer|\App\Supplier $customerOrSupplier
     **/
    function check_for_address_info($customerOrSupplier) {
    }
    

    【讨论】:

    • 扩展类是最有意义的,也是最合乎逻辑的。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2021-03-29
    • 1970-01-01
    • 2012-06-02
    • 2022-01-09
    • 1970-01-01
    • 2012-07-03
    • 2021-09-25
    • 1970-01-01
    相关资源
    最近更新 更多