SoFunction
Updated on 2025-03-06

Laravel's judgment practices of servers in different production environments

In the early stage of the project, a single application will be used for development speed, which is a Laravel framework to implement APIs and background interfaces.

After the user size increases, one server is not enough, so the project uses API and backend interface to open it to different servers.

It is found that the number of routes has increased and the performance has been affected. At this time, it is necessary to different servers to load different routes.

How to distinguish the environment of different servers, but also the production environment.

Code implementation

Availableapp()->environment(); Method implementation, the difference between production environment and test environment.

After checking the code, I found that there are more methods available.

/**
  * Get or check the current application environment.
  *
  * @return string|bool
  */
public function environment()
{
  // Returns the number of parameters passed to the function  if (func_num_args() > 0) {
    // If the first parameter is an array, go to the first one, if not, take all of it.    $patterns = is_array(func_get_arg(0)) ? func_get_arg(0) : func_get_args();

    return Str::is($patterns, $this['env']);
  }

  return $this['env'];
}

The Str::is function determines whether the given string matches the given pattern. Asterisk * can be used to represent wildcard characters:

#Judge in the API environmentapp()->environment("");
#Judge in ADMIN environmentapp()->environment("");
# Judge in all environmentsapp()->environment("production.*");

Revise RouteServiceProvider document

/**
 * Define the routes for the application.
 */
public function map()
{
  // Public routing
  if (app()->environment('')) {
    # production api routing    $this->mapApiRoutes();
  } elseif (app()->environment('')) {
    # production admin routing    $this->mapAdminRoutes();
  } else {
    # local testing stanging environment to load all routes    $this->mapApiRoutes();

    $this->mapAdminRoutes();
  }
}

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.