用 symfony/options-resolver 優雅的校驗類初始化選項

示例類

use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * Class Email
 * composer require symfony/options-resolver
 */
class Email
{
    /**
     * Email constructor.
     *
     * @param  array  $options
     */
    public function __construct(array $options = [])
    {
        $this->configureOptions($options, function (OptionsResolver $resolver){
            $resolver->setDefaults([
                'host'     => 'smtp.example.org',
                'username' => 'user',
                'password' => 'password',
                'port'     => 25,
            ]);
            $resolver->setRequired(['host', 'username', 'password', 'port']);
            $resolver->setAllowedTypes('host', 'string');
            $resolver->setAllowedTypes('username', 'string');
            $resolver->setAllowedTypes('password', 'string');
            $resolver->setAllowedTypes('port', 'int');
        });
    }

    /**
     * @param  array  $options
     * @param  \Closure  $closure
     */
    public function configureOptions(array $options, Closure $closure)
    {
        $resolver = new OptionsResolver;
        $closure($resolver);
        $this->options = $resolver->resolve($options);
    }
}

正確的選項

$email = new Email([
    'host'     => 'smtp.example.org',
    'username' => 'user',
    'password' => 'password',
    'port'     => 25,
]);

var_export($email);
Email::__set_state(array(
    'options' =>
        array (
            'host' => 'smtp.example.org',
            'username' => 'user',
            'password' => 'password',
            'port' => 25,
        ),
))

未經過校驗的選項

$email = new Email([
    'host'     => 'smtp.example.org',
    'username' => 'user',
    'password' => 'password',
    'port'     => '25', // 注意這裏
]);

var_export($email);
PHP Fatal error:  Uncaught Symfony\Component\OptionsResolver\Exception\InvalidOptionsException: The option "port" with value "25" is expected to be of type "int", but is of type "string".

總結

我的以爲可以使用該 symfony/options-resolver 組件較好的對開發第三方 sdk 的客戶端類初始化參數進行校驗,例如我的適配的 Yii 極光推送擴展包 - yii-jpush 中的應用。php

相關文章
相關標籤/搜索