search
HomeBackend DevelopmentPHP TutorialHours is an environment variable, I will use ENV. Calm down, calm down, let me tell you something first

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
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
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
Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

PHP Logging: Best Practices for PHP Log AnalysisPHP Logging: Best Practices for PHP Log AnalysisMar 10, 2025 pm 02:32 PM

PHP logging is essential for monitoring and debugging web applications, as well as capturing critical events, errors, and runtime behavior. It provides valuable insights into system performance, helps identify issues, and supports faster troubleshoot

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Explain the concept of late static binding in PHP.Explain the concept of late static binding in PHP.Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Customizing/Extending Frameworks: How to add custom functionality.Customizing/Extending Frameworks: How to add custom functionality.Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools