Home  >  Article  >  PHP Framework  >  Examples prove that ChatGPT has a great impact on ordinary programmers!

Examples prove that ChatGPT has a great impact on ordinary programmers!

藏色散人
藏色散人forward
2023-03-17 15:52:451384browse

This article brings you relevant knowledge about ChatGPT. It mainly talks about how I use an example to prove the impact or help of ChatGPT on our ordinary programmers? Friends who are interested can take a look below. I hope it will be helpful to everyone.

I just saw a question in the community. I want to ask how to elegantly write the following judgment logic:
(It can be seen that there is quite a lot of judgment logic and does not need to be detailed. Look)

腐植酸含量 30 g/L(不低于 30 g/L)(右边有 +- 键,可以增加或减少,但净含量不低于 30 g/L)。大量元素含量(合计不低于 200 g/L):氮 70 g/L (下边有两个选择,UAN 或氮,每个健右边有 +- 键,可以增加或减少,下同), 磷 70 g/L (下边有两个选择,磷酸一铵或磷酸二铵,每个健右边有 +- 键,可以增加或减少,下同),钾 60 g/L (下边有四个选择,氯化钾、硫酸钾、硝酸钾或磷酸二氢钾,每个健右边有 +- 键,可以增加或减少,下同)。至少包括两种元素,单一元素净含量不低于 20 g/L,氮、磷、钾三个相加不能低于 200 g/L,低于 200 g/L 弹出错误提示。
游离氨基酸 100 g/L(不低于 100 g/L)(右边有 +- 键,可以增加或减少,但净含量不低于 100 g/L),微量元素(不低于 20 g/L):铁 4 g/L (每个右边有 +- 键,可以增加或减少,至少包括 1 种微量元素,6 种元素净含量总和不低于 20 g/L,低于则有错误提示。若添加任一微量元素,不低于 0.5 g/L,低于则有错误提示)、锌 4g/L、硼 4g/L、铜 4g/L、锰 3.5g/L、钼 0.5g/L(右边有 +- 键,可以增加或减少,钼净含量不能高于 5 g/L,高于则有错误提示)

Thinking back to this, I would always ask ChatGPT to see if it is as amazing as the ones uploaded on the Internet.
So I sent the original question to ChatGPT and got the following answer:
(Because my network is not that stable, the answer I got often said that the network was disconnected halfway through. , so only part of the examples are passed)

ChatGPT answer version 1.1

In the Laravel framework, you can use the form validator to verify the conditions, specifically The implementation steps are as follows:

  • Create a custom validation rule

In the Laravel framework, you can use php artisan make:rule command to create a custom validation rule class. This custom validation rule class needs to implement the Illuminate\Contracts\Validation\Rule interface and write the logic of the validation rules in it.
For example, you can create a custom validation rule class named FertilizerRule for validating fertilizer conditions:

$ php artisan make:rule FertilizerRule

In the FertilizerRule class, you can implement passes method to verify, if the verification is successful, return true, otherwise return false:

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class FertilizerRule implements Rule
{
    public function passes($attribute, $value)
    {
        // TODO: 编写肥料条件的验证逻辑
    }

    public function message()
    {
        return 'The :attribute is invalid.';
    }
}
  • Writing verification Logic

In the FertilizerRule class, you can write verification logic for fertilizer conditions according to the requirements of the question. The following is an example:

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class FertilizerRule implements Rule
{
    public function passes($attribute, $value)
    {
        // 验证腐植酸含量
        if (!isset($value[&#39;humic_acid&#39;]) || $value[&#39;humic_acid&#39;] < 30) {
            return false;
        }

        // 验证大量元素含量
        $total_npk = $value[&#39;nitrogen&#39;] + $value[&#39;phosphorus&#39;] + $value[&#39;potassium&#39;];
        if ($total_npk < 200) {
            return false;
        }
        if ($value[&#39;nitrogen&#39;] < 70 || $value[&#39;phosphorus&#39;] < 70 || $value[&#39;potassium&#39;] < 60) {
            return false;
        }

        // 验证至少包括两种元素,单一元素净含量不低于 20 g/L
        $count = 0;
        foreach ([&#39;nitrogen&#39;, &#39;phosphorus&#39;, &#39;potassium&#39;] as $element) {
            if ($value[$element] >= 20) {
                $count++;
            }
        }
        if ($count < 2) {
            return false;
        }

        // 验证游离氨基酸含量
        if (!isset($value[&#39;amino_acid&#39;]) || $value[&#39;amino_acid&#39;] < 100) {
            return false;
        }

        // 验证微量元素含量
        $total_trace = 0;
        $trace_elements = [&#39;iron&#39;, &#39;zinc&#39;, &#39;boron&#39;, &#39;copper&#39;, &#39;manganese&#39;, &#39;molybdenum&#39;];
        foreach ($trace_elements as $element) {
            if (isset($value[$element])) {
                $total_trace += $value[$element];
            }
        }
        if (count(array_filter($value, function ($v) { return $v >= 0.5; })) < 1 || $total_trace < 20 ||
    //...代码不完整

It seems that there is quite a difference between the elegance required by the topic, so I continued to ask

me: I don’t feel like it Too elegant, using too many ifs, not very clear, please optimize it

ChatGPT answer version 1.2

Yes, This code does have a lot of if statements, making the code difficult to read and maintain. I would suggest breaking this code into multiple functions, each responsible for handling only one specific condition. This makes the code clearer and easier to read and maintain.
Here is a possible optimization:

 function validateHumicAcid($value) {
    return $value >= 30;
}

function validateMacroElements($nitrogen, $phosphorus, $potassium) {
    $sum = $nitrogen + $phosphorus + $potassium;
    return $sum >= 200 && $nitrogen >= 20 && $phosphorus >= 20 && $potassium >= 20;
}

function validateTraceElements($iron, $zinc, $boron, $copper, $manganese, $molybdenum) {
    $sum = $iron + $zinc + $boron + $copper + $manganese + $molybdenum;
    $atLeastOne = $iron >= 0 || $zinc >= 0 || $boron >= 0 || $copper >= 0 || $manganese >= 0 || $molybdenum >= 0;
    $atLeastSix = $sum >= 20;
    return $atLeastOne && $atLeastSix && $molybdenum <= 5;
}

function validateAminoAcids($value) {
    return $value >= 100;
}

function validate($humicAcid, $nitrogen, $phosphorus, $potassium, $iron, $zinc, $boron, $copper, $manganese, $molybdenum, $aminoAcids) {
    $isValid = true;

    if (!validateHumicAcid($humicAcid)) {
        $isValid = false;
        // 输出错误提示
    }

    if (!validateMacroElements($nitrogen, $phosphorus, $potassium)) {
        $isValid = false;
        // 输出错误提示
    }

    if (!validateTraceElements($iron, $zinc, $boron, $copper, $manganese, $molybdenum)) {
        $isValid = false;
        // 输出错误提示
    }

    if (!validateAminoAcids($aminoAcids)) {
        $isValid = false;
        // 输出错误提示
    }

    return $isValid;
}

Now, we have broken down the validation logic into four independent functions, each focused on handling a specific condition. This makes the code more concise and easier to understand.

Finally, we combine these functions and use them in the validate function to validate the input value. If the input is invalid, false is returned and an error message is output. Otherwise, returns true.

It should be noted that the error prompts here are marked by comments and should actually be output through the error handling mechanism provided by the Laravel framework.

You can seeChatGPTAccording to my question, I changed it to use a function to solve this problem
I will continue to ask:
me: It still doesn’t feel elegant. Please use the laravel framework and use the responsibility chain design pattern to design this request

ChatGPT answer version 1.3

Okay, let me show you how to design this requirement using the Laravel framework and the chain of responsibility design pattern.
First, we need to define a validator class to verify whether each condition is met. This class can implement the Illuminate\Contracts\Validation\Validator interface in the Laravel framework, so that it can be easily integrated with Laravel's built-in validator component.

Next, we can define an abstract base class Validatable, which defines an abstract method validate to verify whether the input value meets the specified conditions. We can define a specific validator class based on each condition. These classes inherit from Validatable and implement the validate method for specific verification.

Finally, we can use the chain of responsibility pattern to organize these validator classes so that they validate the input values ​​in sequence. Each validator class can set a next attribute that holds an instance of the next validator class. In the validate method, if the current validator fails to validate, the validate method of the next validator will be called, and so on, until all validators have been validated or one validator fails.

The following is a sample code for verifying the two conditions of humic acid content and macroelement content:

<?php

namespace App\Validators;

use Illuminate\Contracts\Validation\Validator;

abstract class Validatable implements Validator
{
    protected $next;

    public function setNext(Validatable $next)
    {
        $this->next = $next;
        return $next;
    }

    public function validate($attribute, $value, $parameters = [], $validator = null)
    {
        if ($this->condition($value)) {
            return true;
        } elseif ($this->next) {
            return $this->next->validate($attribute, $value, $parameters, $validator);
        } else {
            return false;
        }
    }

    abstract protected function condition($value);
}

class HumicAcidValidator extends Validatable
{
    protected function condition($value)
    {
        return $value >= 30;
    }
}

class NitrogenValidator extends Validatable
{
    protected function condition($value)
    {
        return $value >= 70;
    }
}

class PhosphorusValidator extends Validatable
{
    protected function condition($value)
    {
        return $value >= 70;
    }
}

class PotassiumValidator extends Validatable
{
    protected function condition($value)
    {
        return $value >= 60;
    }
}

class ValidatorChain implements Validator
{
    protected $chain;

    public function __construct()
    {
        $this->chain = new HumicAcidValidator();
        $this->chain->setNext(new NitrogenValidator())
                    ->setNext(new PhosphorusValidator())
                    ->setNext(new PotassiumValidator());
    }

    public function validate($attribute, $value, $parameters = [], $validator = null)
    {
        return $this->chain->validate($attribute, $value, $parameters, $validator);
    }
}

Summary

You can see ChatGPTThey gave me a relatively appropriate answer to my questions

Although these codes cannot be directly applied to actual projects, they also gave us some Ideas, how to implement the three versions of the answers in the above examples? A novice like me may only be able to think of the first two ways to solve the problem.

ChatGPTIt is equivalent to giving me some new methods and ideas to solve the problem, or methods and ideas that I don’t know

If I don’t know about certain functions in the future For ideas, why not ask ChatGPT~

Recommended study: "laravel video tutorial"

The above is the detailed content of Examples prove that ChatGPT has a great impact on ordinary programmers!. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:learnku.com. If there is any infringement, please contact admin@php.cn delete