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

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

Mar 17, 2023 pm 03:52 PM
laravel programmer chatgpt

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 弹出错误提示。
Copy after login
游离氨基酸 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,高于则有错误提示)
Copy after login

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
Copy after login

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.';
    }
}
Copy after login
  • 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 ||
    //...代码不完整
Copy after login

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;
}
Copy after login

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);
    }
}
Copy after login

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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to get the return code when email sending fails in Laravel? How to get the return code when email sending fails in Laravel? Apr 01, 2025 pm 02:45 PM

Method for obtaining the return code when Laravel email sending fails. When using Laravel to develop applications, you often encounter situations where you need to send verification codes. And in reality...

How to implement the custom table function of clicking to add data in dcat admin? How to implement the custom table function of clicking to add data in dcat admin? Apr 01, 2025 am 07:09 AM

How to implement the table function of custom click to add data in dcatadmin (laravel-admin) When using dcat...

Laravel Redis connection sharing: Why does the select method affect other connections? Laravel Redis connection sharing: Why does the select method affect other connections? Apr 01, 2025 am 07:45 AM

The impact of sharing of Redis connections in Laravel framework and select methods When using Laravel framework and Redis, developers may encounter a problem: through configuration...

Laravel multi-tenant extension stancl/tenancy: How to customize the host address of a tenant database connection? Laravel multi-tenant extension stancl/tenancy: How to customize the host address of a tenant database connection? Apr 01, 2025 am 09:09 AM

Custom tenant database connection in Laravel multi-tenant extension package stancl/tenancy When building multi-tenant applications using Laravel multi-tenant extension package stancl/tenancy,...

Laravel Eloquent ORM in Bangla partial model search) Laravel Eloquent ORM in Bangla partial model search) Apr 08, 2025 pm 02:06 PM

LaravelEloquent Model Retrieval: Easily obtaining database data EloquentORM provides a concise and easy-to-understand way to operate the database. This article will introduce various Eloquent model search techniques in detail to help you obtain data from the database efficiently. 1. Get all records. Use the all() method to get all records in the database table: useApp\Models\Post;$posts=Post::all(); This will return a collection. You can access data using foreach loop or other collection methods: foreach($postsas$post){echo$post->

How to effectively check the validity of Redis connections in Laravel6 project? How to effectively check the validity of Redis connections in Laravel6 project? Apr 01, 2025 pm 02:00 PM

How to check the validity of Redis connections in Laravel6 projects is a common problem, especially when projects rely on Redis for business processing. The following is...

Laravel's geospatial: Optimization of interactive maps and large amounts of data Laravel's geospatial: Optimization of interactive maps and large amounts of data Apr 08, 2025 pm 12:24 PM

Efficiently process 7 million records and create interactive maps with geospatial technology. This article explores how to efficiently process over 7 million records using Laravel and MySQL and convert them into interactive map visualizations. Initial challenge project requirements: Extract valuable insights using 7 million records in MySQL database. Many people first consider programming languages, but ignore the database itself: Can it meet the needs? Is data migration or structural adjustment required? Can MySQL withstand such a large data load? Preliminary analysis: Key filters and properties need to be identified. After analysis, it was found that only a few attributes were related to the solution. We verified the feasibility of the filter and set some restrictions to optimize the search. Map search based on city

Laravel database migration encounters duplicate class definition: How to resolve duplicate generation of migration files and class name conflicts? Laravel database migration encounters duplicate class definition: How to resolve duplicate generation of migration files and class name conflicts? Apr 01, 2025 pm 12:21 PM

A problem of duplicate class definition during Laravel database migration occurs. When using the Laravel framework for database migration, developers may encounter "classes have been used...

See all articles