Directory Structure

Other Directories

Overview

The directory structure of a Laravel application i.e ECOM-API is designed to organize the application’s components in a logical and efficient way. Each directory serves a specific purpose in the framework. Here’s a detailed breakdown of the ECOM-API application directory structure:

After Successfully cloning the repository You will get the structure like this->

toolstation-ecom-api/
├── app/
├── bin/
├── bootstrap/
├── config/
├── database/
├── public/
├── resources/
├── routes/
├── storage/
├── tests/
├── vendor/
├── .env
├── .gitignore
├── artisan
├── composer.json
├── composer.lock
└── phpunit.xml

Table of Contents

bin-directory

bin/
├── build-docker-image.sh
├── build-for-skaffold.sh
├── container-pre-start.sh

Purpose: Contains executable scripts for the Laravel application. This directory is typically used for the laravel executable, which can be used to run Artisan commands and other tasks.

A script to run Laravel commands

1. build-docker-image.sh

Purpose: This script in the file build-docker-image.sh is used for building and pushing a Docker image of your Ecom application to a container registry.

  • Check IMAGE_TAG: Ensures that an IMAGE_TAG environment variable is provided, which is used to tag the Docker image. If not present, the script aborts.
if [ -z "$IMAGE_TAG" ]; then
    echo "IMAGE_TAG is not present. This is required. Aborting!"
    exit 1
else
    echo "Building new EPOS API image with Tag : $IMAGE_TAG"
fi
echo "Removing all application/framework caches"
php artisan route:clear
php artisan view:clear
php artisan config:clear
php artisan optimize:clear
php artisan event:clear

These commands clear various caches to ensure that the Docker image is built with the latest application state.

  • Build Docker Image:

docker build -t "eu.gcr.io/toolstation-images/ecom-api:$IMAGE_TAG" .

Builds the Docker image with the specified tag.

  • Push Docker Image:

docker push "eu.gcr.io/toolstation-images/ecom-api:$IMAGE_TAG" Pushes the newly built Docker image to the specified container registry.

2. build-for-skaffold.sh

This script in the file build-for-skaffold.sh is used for building Docker images with support for Skaffold, which is a tool for continuous development on Kubernetes.

  • Check NAMESPACE and RELEASE_ID: Ensures that both NAMESPACE and RELEASE_ID environment variables are set. These are required for deployment.
  • In our Project as follows:
if [ -z "$NAMESPACE" ]; then
    echo "NAMESPACE is not present. This is required. Aborting!"
    exit 1
else
    echo "Building for deployment to namespace: '$NAMESPACE'"
fi

Summary: Facilitates Docker image building and deployment in a Kubernetes environment with Skaffold, with conditional handling for full builds and symlinked dependencies.

3. container-pre-start.sh

This script in the file container-pre-start.sh is intended to run before the application container starts, usually to ensure that certain Laravel application optimizations and setups are in place.

  • Optimize Laravel Application:
    php artisan optimize >&2

This command optimizes the Laravel application, including various performance enhancements.

  • Publish Horizon Assets:
    php artisan horizon:publish

Ensures that the latest assets for Laravel Horizon (a queue manager) are published, which might be necessary for proper operation.

Summary: Prepares the Laravel application for optimal performance and correct operation of Horizon by running necessary Laravel commands.

bootstrap-directory

bootstrap/
├── cache/
├── app.php

the bootstrap directory plays a critical role in setting up and initializing the application. It contains files and folders that are essential for configuring and starting the Laravel application. In your case, the bootstrap directory includes a cache folder and a app.php file.

bootstrap/cache Directory

  • Purpose: The cache directory within the bootstrap folder is used by Ecom to store various cached files. These cached files improve performance by storing precompiled files and other configuration data that the application needs to operate efficiently.
  • Typical Cached Files
    • Configuration Cache (config.php)
    • Route Cache (routes.php)
    • Services Cache (services.php)
  • In Ecom Application:
    • Services Cache (services.php): This file stores a cached list of application services. Caching service lists reduces the overhead of reloading and re-registering services on every request.
      • How It Works: During the bootstrapping process, Laravel reads this cached file instead of processing service providers and bindings from scratch. This speeds up the application by reducing the overhead of loading and parsing configuration and service provider data on each request.
    • Package Cache (packages.php): The packages.php file in the bootstrap/cache directory is used to cache information related to the Laravel packages installed in Ecom application. This includes data about package service providers and their configurations.
      • How It Works: Caching package information allows Laravel to bypass the discovery and loading of package service providers on each request. Instead, Laravel can quickly access the cached data, enhancing performance.

app.php File

The app.php file is a critical part of the Laravel bootstrapping process. Its main role is to create and return the Laravel application instance. This instance is used throughout the application to manage services, handle requests, and manage the application's lifecycle.

Initializes the Laravel application by creating an application instance, binding essential interfaces to the service container, and returning the application instance for use in managing requests and responses.

Detailed Breakdown

  • Create The Application Instance
$app = new Illuminate\Foundation\Application(
    $_ENV['APP_BASE_PATH'] ?? dirname(__DIR__)
);
  • What It Does: This line creates a new instance of the Laravel application. The Illuminate\Foundation\Application class is the heart of Laravel’s framework, acting as the service container where all dependencies and services are managed.
  • How It Works: $_ENV['APP_BASE_PATH'] provides a base path for the application, with a fallback to the parent directory of the current file if the environment variable is not set. This base path is used to locate other parts of the application.

Binding these interfaces as singletons ensures that Laravel uses a single instance of each class for the entire application lifecycle. This improves efficiency and consistency by reusing the same instances rather than creating new ones for each request.

| Bind Important Interfaces
$app->singleton(
    Illuminate\Contracts\Http\Kernel::class,
    App\Http\Kernel::class
);

$app->singleton(
    Illuminate\Contracts\Console\Kernel::class,
    App\Console\Kernel::class
);

$app->singleton(
    Illuminate\Contracts\Debug\ExceptionHandler::class,
    App\Exceptions\Handler::class
);

Return The Application Instance

return $app;

This line returns the application instance created earlier. This instance is used by other parts of the Laravel framework (such as the public/index.php front controller) to handle incoming requests and generate responses.

config-directory

The config directory in a Laravel application is fundamental for managing the application's configuration settings. Each file in the config directory typically corresponds to a specific aspect of the application's configuration. Here’s a detailed explanation of some key configuration files found in Ecom application, including their purpose and usage:

Some of the Explanation of Key Configuration Files:

  1. app.php:
  • Purpose: The app.php file is the main configuration file for the Laravel application. It contains general settings and options for the application.
 'name' => env('APP_NAME', 'EPOS_API_DEV'),
 'debug' => env('APP_DEBUG', false),
 // Others..
'providers' => [
         /*
         * Laravel Framework Service Providers...
         */
        Illuminate\Auth\AuthServiceProvider::class,
        Illuminate\Broadcasting\BroadcastServiceProvider::class,
        Illuminate\Bus\BusServiceProvider::class,
        Illuminate\Cache\CacheServiceProvider::class,
  • Contents:
    • Name and Environment: Defines the application name and environment settings.
    • Debug Mode: Controls whether debugging information should be displayed.
    • URL and Timezone: Sets the base URL of the application and the default timezone.
    • Locale and Fallback Locale: Specifies the default locale and a fallback locale for localization.
    • Service Providers: Lists the service providers that are registered with the application.
    • Aliases: Defines class aliases used in the application.
    • Usage: This file is essential for setting up basic application-wide configurations. For instance, changing the debug setting to true will show detailed error messages, which is useful during development but should be set to false in production.

Other Common Configuration Files:

  • broadcasting.php: Configures real-time event broadcasting.
  • database.php: Manages database connections and settings.
  • mail.php: Configures mail settings.
  • queue.php: Sets up queue connections and job handling.
  • services.php: Defines settings for third-party services and APIs.
  • session.php: Configures session management.
  • view.php: Sets up view paths and caching.

Note: For In detail of these many more files go to packages requires documentation page.

  1. config/toolstation/ directory

The toolstation directory within the config directory of your Laravel application appears to contain configuration files specific to the Toolstation component or service that your application uses.

Purpose of the toolstation Configuration Folder

The toolstation configuration folder is likely used to manage settings related to the Toolstation services and integrations within your Laravel application. Each file within this folder would typically contain settings specific to various aspects of the Toolstation services or components your application relies on.

Here’s an example configuration file in the directory:

<?php

return [
    'service' => env('CONTENT_SERVICE_CLASS', \Toolstation\Content\Services\Wordpress\WordPressContentService::class),

    'wordpress' => [
        'rest_url' => env('WORDPRESS_REST_URL', false),
        'per_page' => 12,
    ],

    'news' => [
        // Additional settings for news can be included here
    ],
];

database-directory

The database/ directory in a Ecom application is used for managing the database aspects of the application.

database/
├── factories/
├── seeders/
  1. factories/
  • Purpose: Holds model factory classes for generating dummy data.
  • Usage: Factories are used in conjunction with seeders and testing to create instances of models with randomized or fixed attributes.
  1. seeders/
  • Purpose: Contains seeder classes used to populate the database with sample or default data.
  • Usage: Seeders are used to insert initial data into the database tables, which is useful for development and testing.

public-directory

public/ Directory: The web root of a Ecom (laravel) application where publicly accessible files are stored.

  • Key Files:
    • index.php: Front controller for handling requests.
    • /.htaccess: Configuration file for URL rewriting (Apache).
    • /robots.txt: Instructions for search engine crawlers.
    • /favicon.ico: Site icon for browser tabs.
  • Directories:
    • /css/, /js/, /images/: Directories for static assets.
    • /storage/: Symlink to storage/app/public for publicly accessible files.

The public/ directory is crucial for managing and serving static assets and providing the entry point for your Laravel application, ensuring proper routing and access to necessary files.

index.php

Register The Auto Loader

require __DIR__.'/../vendor/autoload.php';

  • Purpose: Loads the Composer autoloader.
    • Usage: The autoloader is responsible for automatically including PHP classes from the vendor directory. This eliminates the need to manually include each class file and ensures that all dependencies and libraries are properly loaded.

resources-directory

The resources directory in a Ecom application is used to store various assets and resources that are required for the application's frontend and localization. It is organized into several subdirectories and files that play different roles in the development process. Below is a detailed breakdown of the contents and their purposes:

resources/
    ├── views/
    │   ├── emails/
    │   │   ├── careForm/
    │   │   │   ├── html.blade.php
    │   │   │   └── plain.blade.php
    │   │   ├── feedback/
    │   │   │   ├── html.blade.php
    │   │   │   └── plain.blade.php
    │   └── signin-request.blade.php
    └── lang/
        └── en/
            ├── auth.php
            ├── pagination.php
            ├── password.php
            └── validation.php  

Structure and Contents

1. views/ Directory

In Ecom Application, Blade templates for emails are stored in the resources/views directory, typically under an emails subdirectory. These templates define how email content should be rendered, both in HTML and plain text formats.

  • This directory contains subdirectories for different types of emails, such as careForm and feedback. Each type typically includes two versions of the email template:
    • html.blade.php: This file contains the HTML version of the email. It allows for rich formatting and styling using HTML and inline CSS.
    • plain.blade.php: This file contains the plain text version of the email. This version is used for email clients that do not support HTML or for users who prefer plain text emails.
    • Blade Template Content
        @extends('toolstation/notifications::email.template')
        @section('content')
        // content here...
        @endsection
    
    • @extends('toolstation/notifications::email.template'): This directive extends a base email template provided by the toolstation/notifications package or your custom notification package. It allows you to reuse a common layout for your emails.
    • @section('content'): Defines the content section that will be injected into the base email layout. Here, you use HTML to format the email body.

Usage in the Project

  • Email Sending: When sending an email using Laravel, you specify both the HTML and plain text templates. Laravel will automatically select the appropriate format based on the recipient's email client capabilities.
  • Mailable Classes: You use Mailable classes to define which email templates to use. For example:
      app/
       └── Mail/
            ├── CareForm.php
            └── Feedback.php
    
    

Example: It is Used in CareFormController class as:

  app/Http/Controllers/Api/CareFormController.php
  class CareFormController extends Controller
  {
     public function __invoke(CareFormRequest $request): JsonResponse
     {
        Mail::queue(new CareForm($request->validated()));
        return response()->json('', Response::HTTP_OK);
     }
  }
  • The CareForm class is responsible for sending customer care form emails.
  • The Feedback class is for sending feedback-related emails.

2. lang/ Directory

Purpose: Stores language files for localization. These files help in providing translations and other locale-specific data.

Details:

  • Locale Files: Language files are organized by locale, and each file typically returns an array of language lines.
  • Example: In Ecom Project we have an English locale, which might have en subdirectories, each containing translation files.
resources/lang/
    ├── en/
    │   └── messages.php

routes-directory

In the Ecom application, the routes directory contains all the route definitions for the application. These route files are used to define the various endpoints that the application responds to. Each file serves a specific purpose based on the type of routes it contains.

Ecom routes/ Directory Structure

routes/
├── api.php
├── channels.php
├── console.php
├── endpoints.php
└── web.php

Route Files Explained

1. api.php

The api.php file is used to define routes that are part of the API of the application. Routes defined in this file are automatically assigned the api middleware group, which includes features such as rate limiting and API authentication

Example:

   <?php
   use Illuminate\Support\Facades\Route;
   if (config('app.expose_cache_test_endpoint')) {
   Route::get('/cache-test', 'CacheTestController');
   }
   // other config..
   Route::get('/health-check', 'PingController');
   Route::middleware(config('auth.basic_auth.enabled') ? 'auth.basic.api' : [])->group(base_path('routes/endpoints.php'));

  • Dynamic Routes: Uses config() to determine if certain routes should be exposed.
  • Middleware: Applies middleware conditionally and includes additional routes from endpoints.php.
  • base_path('routes/endpoints.php'): dynamically includes the endpoints.php file, allowing you to manage routes from a separate file.

2. channels.php

The channels.php file is used to define the channels for broadcasting events. This file is where you specify which channels are available for the application's real-time event broadcasting.

3. console.php

This file defines a custom Artisan command named submit-outstanding-orders-for-settlement. Artisan commands are Laravel’s way of defining console commands that can be executed via the command line.

Artisan::command('submit-outstanding-orders-for-settlement', function () {
    // Command logic
});

How to Use:

Run the Command: Execute the command from the terminal to process outstanding payments:

php artisan submit-outstanding-orders-for-settlement
  • Purpose: Useful for backend operations that need to be executed periodically or on-demand, such as processing payments and handling transactions.

4.endpoints.php

The endpoints.php file is used to define routes that belong to certain parts of the API, particularly those that might require special middleware or configurations. It allows for clear separation of route definitions based on functionality, making it easier to manage and maintain the routing logic.

Note: This file is included in api.php conditionally based on the configuration of middleware.

Structure and Usage of endpoints.php

  • Namespace and Imports: At the beginning of the file, necessary namespaces and classes are imported. This includes controller classes and Laravel's Route facade.
  • Routing Definitions: Routes are defined to handle various API requests. The routing configuration typically involves specifying HTTP methods, URIs, and the corresponding controller methods.
Route::get('/_ping', 'PingController');
  • /_ping: This route is used for a simple health check to verify that the API is up and running. It calls the PingController.
  • Grouped Routes: Routes related to specific entities or functionalities are grouped under a common prefix for better organization.
Route::prefix('customers')->group(static function () {
Route::get('/_ping', 'PingController');
Route::get('/{customerId}', 'CustomerController@get');
// Other endpoints
);
  • Prefixing: Routes that deal with customer-related operations are grouped under the customers prefix. This helps in logically organizing routes related to customer information and operations.
  • Key Notes: The use of prefixes and route grouping in endpoints.php helps in organizing related routes together, which improves readability and maintainability of the code.

storage-directory

The storage directory is used to store various types of data that your Laravel application needs to persist. This includes logs, cached files, file uploads, and application-generated data.

storage/
├── app/
├── framework/
├── trade-credit/
└── logs/

Subdirectories and Their Usage

1. app/

  • Purpose: This is where application-specific files are stored, such as file uploads or generated files.
  • Usage: You might store user-uploaded files here or any other files that need to be generated and persisted by the application.

2. framework/

  • Purpose: Contains framework-generated files, including cache files and sessions.
  • Subdirectories:
    • cache: Stores cache files generated by the application.
    • sessions: Stores session data if you use file-based session storage.
    • views: Stores compiled Blade templates.

3. trade-credit/

  • Purpose: is used to manage and store files related to trade credit operations.
  • Accessing File: $url = Storage::disk('local')->url('trade_credit/terms_and_conditions.pdf');

4. logs/

  • Purpose: Contains framework-generated files, including cache files and sessions.

tests-directory

The tests directory is used to store your application’s test files. It is a crucial part of the development workflow, allowing you to write and run automated tests to ensure your application’s functionality and stability.

tests/
├── Feature/
├── Unit/
├── Mocks/
├── Integration/
├── Data/
└── TestCase.php

1. Feature/

  • Purpose: This directory contains feature tests, which are used to test the application’s high-level functionality. Feature tests typically interact with the entire application, simulating real-world user interactions, such as HTTP requests and responses.
  • Examples:
    • Testing Account Card Request Endpoints.
    • Example File: tests/Feature/AccountCardRequestEndpointsTest.php

2. Unit/

  • Purpose: This directory is for unit tests, which test individual components or methods in isolation. Unit tests are focused on small pieces of code, like a specific class or function, without involving the application’s broader context.

3. Mocks/

  • This directory likely contains mock objects or data used to simulate the behavior of real objects during testing. Mocks are often used in unit tests to simulate dependencies and isolate the unit of code being tested.

4.TestCase.php

  • This is likely a PHP file that defines a base test case class. In many testing frameworks, a base test case class provides common functionality or setup code that other test classes can inherit. This helps reduce code duplication and centralizes test configuration.

Usage in the Ecom:

  • handle complex relationships between models, especially with orders and parent orders, which shows a deep integration of your test cases with your application's logic.
  • Handling Optional Overriding Logic:
    • In mockBraintreeCreateTransaction, there's a mix of required and optional parameters. Use default values for optional parameters and validate them to ensure your mocks work as expected.

vendor-directory

The vendor directory is where Composer (the PHP dependency manager) installs and maintains third-party libraries and packages required by your project. This directory is crucial for managing dependencies, autoloading classes, and ensuring that your application has access to the libraries it needs.

Usage With The Ecom Application:

1. Dependency Management:

  • Composer Installation: Use Composer to manage the dependencies of your project. Running composer install will populate the vendor directory with all required packages based on the composer.json file.
  • Updating Dependencies: Use composer update to fetch the latest versions of your dependencies as specified in the composer.json file. This will also update the vendor directory.

2. Autoloading:

  • Composer automatically generates an autoload file (vendor/autoload.php) that you should include in your project to access the classes from the dependencies. This file helps in automatically loading the necessary classes without requiring individual require or include statements.
       require __DIR__.'/vendor/autoload.php';
    

3. Custom Toolstation Package:

 "toolstation/auth": "@dev",
        "toolstation/autoprinter": "@dev",
        "toolstation/carrier": "@dev",

Copyright © 2026