Home Backend Development PHP Tutorial Hours is an environment variable, I will use ENV. Calm down, calm down, let me tell you something first

Hours is an environment variable, I will use ENV. Calm down, calm down, let me tell you something first

Aug 26, 2024 am 08:30 AM

We are always in a rush and wanting to develop as quickly as possible, and we often end up adopting old habits and building old software. An item that we can improve a lot is this little thing called environment, let's understand a little more about this.


First of all, I would like to show here the focus on the concept of configurations for laravel, I will not worry about the remaining standards, such as resources or others like that.

1 - Let's seek knowledge!

A while ago I heard that I couldn't do this ENV pass within my crazy codes, I was like; wow
So the purpose is to understand the reasons, because that way, we can make better decisions as engineers.

1.1 - Correct way or a point of view?

So come on little future master, let's put a value in an environment variable so we can play around, so let's call it:

Horas é uma variável de ambiente, vou usar o ENV. Calma, calma, deixa eu te falar uma coisa antes

Let's go to the first point, great decision in having placed this configuration as an environment variable, this way you make everything easier to manage different environments (Production, approval, If you have one? ) and much safer, because this value will not be exposed when you perform that naughty git push on your repository (git/bitbucket), can you imagine your water secret being leaked on the internet, how sad.

And to retrieve this value in Laravel we can use the env() method or also use another package such as Support from Illuminate (reminds me of minions, I don't know why?)

Horas é uma variável de ambiente, vou usar o ENV. Calma, calma, deixa eu te falar uma coisa antes

env: Laravel Helper (That uses Env::get)
Env::get: Env class from the Support Illuminate package

Wow, it's ready, so why keep inventing fashion? The truth is that this is not a good idea, I will explain why soon, stay with me.
For the different solution, we can mention the configuration files that will retrieve the value of the environment created, so the configuration file is centralized and come on, seriously! much better for reading a code.

In this specific situation you can already use the existing config file, called services.php, but nothing prevents you from creating a file for your specific context.

In the path config/services.php

Horas é uma variável de ambiente, vou usar o ENV. Calma, calma, deixa eu te falar uma coisa antes

And so we will call it in the code as follows:

Horas é uma variável de ambiente, vou usar o ENV. Calma, calma, deixa eu te falar uma coisa antes


2 - Cool, but why should I use configs to retrieve variables and not just fetch them directly?

I'll try to show you some reasons:

2.1 - Increased performance and better IO utilization

Think about the following situation, do you have files in production that will be accessed all the time, carrying out considerable IO, which will increase machine resources and depending on the situation, system slowdowns? (And believe me, until you actually find the problem, you will go through things that will question all your knowledge)

When we talk about the production environment, it is recommended that you cache your beautiful configuration files, with Laravel you can use artisan

php artisan config:cache
Copy after login
e

This beautiful command takes all the configuration files and their respective values ​​and compiles them into a single php file, which increases performance. This is due to the fact that the IO numbers are reduced to 1

Curiosity: When you use this command, env() starts to return NULL because it disables this function. So if from "Neida" a env() yours stopped working, that's it.

Env() Perform IO operation and they are expensive and slow.

It is best to do this operation once at the beginning of the application rather than having to perform the operation every time you need an env.

2.2 - 가능한 최선의 방법으로 조직 및 표준화

모든 설정을 원하는 대로 쉽게 유지할 수 있습니다. 원하는 개 이름을 입력하고, 폴더를 만들고 모든 배열을 원하는 대로 구성하면 구조가 더 깔끔해집니다(적당히 사용해주세요)
예:

이 키를 보세요:

Horas é uma variável de ambiente, vou usar o ENV. Calma, calma, deixa eu te falar uma coisa antes

이제 이 키를 보세요:

Horas é uma variável de ambiente, vou usar o ENV. Calma, calma, deixa eu te falar uma coisa antes

제 소견으로는 1번째가 훨씬 나은 것 같아요

게다가 유사한 구성을 코드에 "무작위로" 배치할 필요 없이 올바른 중앙 집중식 위치에 가질 수 있으며, 애플리케이션에 완전히 적합한 배열을 구성한다는 아이디어가 정말 마음에 듭니다.

새 개발자를 위한 지침은 새 구성을 만드는 위치와 방법을 알려줄 수 있기 때문에 훨씬 간단합니다.

단순하게 유지하고 차이를 만드세요!

지금까지 모든 것에 감사드립니다.

출처:

Laravel 11 구성 문서

The above is the detailed content of Hours is an environment variable, I will use ENV. Calm down, calm down, let me tell you something first. 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)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

See all articles