VOOZH about

URL: https://deepwiki.com/gp247net/shop/1.2-core-architecture-and-service-provider

⇱ Core Architecture and Service Provider | gp247net/shop | DeepWiki


Loading...
Menu

Core Architecture and Service Provider

Purpose and Scope

This document explains the ShopServiceProvider class, which serves as the central integration point for the GP247/Shop package. The service provider is responsible for bootstrapping the entire shop system, registering middleware, loading views, merging configurations, and initializing all shop subsystems.

For information about the database structure created during installation, see Database Schema. For details about initial data seeding and configuration population, see Data Seeders and Initialization.

Overview

The ShopServiceProvider extends Laravel's base ServiceProvider class and acts as the main entry point that integrates the shop package into the GP247 ecosystem. It coordinates the initialization sequence, ensuring all components are properly configured before the application handles requests.


Sources: src/ShopServiceProvider.php1-296

Service Provider Class Structure

The ShopServiceProvider class is defined in the GP247\Shop namespace and contains three primary lifecycle methods plus several supporting methods.

MethodPhasePurpose
register()Early InitializationMerge configurations, register service bindings
boot()Late InitializationLoad resources, register routes/middleware
initial()Called from bootCreate directories, register commands
bootDefault()Called from bootShare models with views
registerRouteMiddleware()Called from bootRegister middleware aliases
validationExtend()Called from bootAdd custom validation rules

Sources: src/ShopServiceProvider.php17-296

The register() Method

The register() method executes during Laravel's early initialization phase, before the application is fully booted. This method focuses on merging configurations and setting up service bindings.


Configuration Merging

The service provider merges package configurations into the application's runtime configuration using Laravel's mergeConfigFrom() method:

Middleware Configuration

The register method adds two middleware to the frontend middleware stack src/ShopServiceProvider.php146-149:

  • check.currency: Handles currency selection and conversion
  • check.email_verified: Enforces email verification requirements

Route Language Exclusions

Customer-related routes are excluded from language prefixing src/ShopServiceProvider.php152-166 because they should maintain consistent URLs regardless of the selected language. This includes routes like customer.index, customer.order_list, customer.order_detail, and others related to customer account management.

File Manager Configuration

The service provider configures Laravel File Manager for shop-specific entity types src/ShopServiceProvider.php169-185 defining folder categories for product, category, brand, supplier, and customer with specific settings:

  • Maximum file size: 30MB
  • Valid MIME types: JPEG, PNG, GIF, SVG, WebP
  • Default view: Grid

Layout Page Registration

Additional layout page types are registered src/ShopServiceProvider.php193-204 to support shop-specific page rendering:

  • shop_item_list: Product listing pages
  • shop_product_detail: Product detail pages
  • shop_product_list: Category product lists
  • shop_profile: Customer profile pages
  • shop_cart: Shopping cart page
  • shop_checkout: Checkout process pages
  • shop_wishlist: Wishlist page
  • shop_compare: Product comparison page
  • shop_auth: Authentication pages
  • shop_search: Search results page

Sources: src/ShopServiceProvider.php139-206

The boot() Method

The boot() method handles late-stage initialization after all service providers have been registered. It performs several critical initialization tasks within try-catch blocks for error handling.


Core Activation Check

The boot process begins with a check to gp247_check_core_actived() src/ShopServiceProvider.php74 If the GP247 Core package is not activated, the shop-specific initialization is skipped. This prevents errors when dependencies are not available.

Helper Function Loading

All PHP files in the Library/Helpers directory are automatically loaded src/ShopServiceProvider.php77-86 using glob() and require_once. This dynamic loading approach allows new helper files to be added without modifying the service provider.

Model Sharing

The bootDefault() method src/ShopServiceProvider.php208-214 shares commonly-used model instances with all views:

  • $modelProduct: ShopProduct model instance
  • $modelOrder: ShopOrder model instance
  • $modelCategory: ShopCategory model instance
  • $modelBrand: ShopBrand model instance

This enables views to access model methods like query scopes and relationships without instantiating the models themselves.

View Namespace Registration

Two view namespaces are registered src/ShopServiceProvider.php108-109:

  • gp247-shop-admin: Points to src/Views/admin, used for admin panel interfaces
  • gp247-shop-front: Points to src/Views/front, used for customer-facing pages

These namespaces allow Blade templates to be referenced using syntax like @include('gp247-shop-admin::component.order_month').

Admin UI Module Registration

The service provider integrates shop-specific components into the admin interface using the gp247_add_module() helper function:

Homepage Modules src/ShopServiceProvider.php112-115:

  • order_month: Monthly order statistics chart
  • new_order: Recent orders widget
  • new_customer: New customer registrations widget
  • top_info: Key performance indicators summary

Header Modules src/ShopServiceProvider.php118:

  • shop_button: Quick access button to shop management in the admin header

Sources: src/ShopServiceProvider.php69-132

The initial() Method

The initial() method is called at the beginning of boot() and handles directory creation, command registration, and publishable resource setup.


Directory Creation

The service provider creates three application directories if they don't exist src/ShopServiceProvider.php23-37:

  • app/GP247/Shop/Api: For custom API controllers
  • app/GP247/Shop/Controllers: For custom frontend controllers
  • app/GP247/Shop/Admin/Controllers: For custom admin controllers

These directories allow developers to extend the package by creating custom controllers that inherit from or override the package's base controllers.

Command Registration

Four Artisan commands are registered src/ShopServiceProvider.php50-55:

Command ClassArtisan CommandPurpose
ShopInstallgp247:shop-installInstall database schema and seed initial data
ShopUninstallgp247:shop-uninstallRemove shop tables and data
ShopSamplegp247:shop-samplePopulate database with sample products and categories
ShopClearCartgp247:shop-clear-cartClean up expired shopping cart sessions

Publishable Resources

The registerPublishing() method src/ShopServiceProvider.php283-289 defines two publishable resource groups:

  • Admin Views (gp247:view-shop-admin): Publishes admin interface views to resources/views/vendor/gp247-shop-admin, allowing customization of admin UI templates
  • Frontend Views (gp247:view-shop-front): Publishes frontend templates to app/GP247/Templates/Default, enabling theme customization

Sources: src/ShopServiceProvider.php20-62 src/ShopServiceProvider.php283-289

Middleware Registration

The service provider defines and registers three middleware components that intercept requests at different stages of the request lifecycle.


Individual Middleware Definitions

The $routeMiddleware property src/ShopServiceProvider.php221-226 defines three middleware aliases:

check.currency (CurrencyMiddleware::class)

  • Handles currency selection and session management
  • Processes currency conversion for product prices
  • Can be applied to routes that require currency awareness

check.email_verified (EmailIsVerifiedMiddleware::class)

  • Verifies that customer accounts have verified email addresses
  • Redirects unverified customers to verification page
  • Applied to customer account and checkout routes

customer.auth (CustomerAuth::class)

  • Authenticates customer sessions
  • Provides frontend authentication separate from admin authentication
  • Guards customer-only routes like profile, orders, and addresses

Middleware Group

The middlewareGroups() method src/ShopServiceProvider.php233-238 creates a customer middleware group that reads its middleware list from gp247-config.shop.middleware. This allows the middleware stack to be configured without modifying code.

Registration Process

The registerRouteMiddleware() method src/ShopServiceProvider.php245-256 performs the actual registration:

  1. Iterates over $routeMiddleware array and calls app('router')->aliasMiddleware() to register each alias
  2. Iterates over middleware groups from middlewareGroups() and calls app('router')->middlewareGroup() to register each group

Sources: src/ShopServiceProvider.php221-256

Validation Extensions

The service provider extends Laravel's validator with custom validation rules specific to shop entities.


product_sku_unique Rule

The product_sku_unique validation rule src/ShopServiceProvider.php265-269 ensures that product SKUs are unique within a store context:

  • Parameters: Takes an optional product ID parameter ($parameters[0]) to exclude the current product when updating
  • Store Context: Uses session('adminStoreId') to scope uniqueness checks to the current store
  • Implementation: Delegates to AdminProduct::checkProductValidationAdmin('sku', $value, $productId, $storeId)

Usage in validation rules:


product_alias_unique Rule

The product_alias_unique validation rule src/ShopServiceProvider.php271-275 ensures that product URL aliases are unique:

  • Parameters: Takes an optional product ID parameter to exclude current product during updates
  • Store Context: Scopes uniqueness to the current store using session('adminStoreId')
  • Implementation: Delegates to AdminProduct::checkProductValidationAdmin('alias', $value, $productId, $storeId)

Usage in validation rules:


Both validation rules support multi-store architecture by checking uniqueness only within the current store context, allowing different stores to use the same SKU or alias for their products.

Sources: src/ShopServiceProvider.php263-276

Error Handling Strategy

The service provider implements comprehensive error handling throughout its initialization sequence to prevent application failures during bootstrapping.

Each major initialization block is wrapped in try-catch blocks src/ShopServiceProvider.php23-127:


This pattern:

  • Catches all errors and exceptions including PHP 7+ Throwable types
  • Formats error messages with context (message, line number, file path)
  • Logs errors using gp247_report() helper function
  • Displays errors to the user for debugging
  • Terminates execution to prevent cascading failures

The only exceptions to this pattern are view loading src/ShopServiceProvider.php108-109 and module registration src/ShopServiceProvider.php112-118 which are considered safe operations that should not halt application startup.

Sources: src/ShopServiceProvider.php20-132

Event Registration Hook

The service provider includes an eventRegister() method src/ShopServiceProvider.php292-295 that is called during boot but currently has no implementation. This method serves as a designated location for registering event listeners and subscribers related to shop operations.

This pattern allows for future extensibility without modifying the boot sequence, enabling developers to add event-driven functionality such as:

  • Product stock level notifications
  • Order status change events
  • Customer registration events
  • Payment processing events

Sources: src/ShopServiceProvider.php129-295

Integration with GP247 Ecosystem

The service provider integrates deeply with the GP247 Core and GP247 Front packages through several mechanisms:


The shop package extends the existing GP247 configuration rather than replacing it:

  • Appends shop middleware to the frontend middleware stack
  • Adds shop routes to the language exclusion list
  • Contributes shop-specific layout page types
  • Injects shop dashboard widgets into the admin homepage

This design allows multiple GP247 packages to coexist and contribute functionality without conflicts.

Sources: src/ShopServiceProvider.php74-204

Summary

The ShopServiceProvider orchestrates the integration of the GP247/Shop package through a well-defined initialization sequence:

PhaseMethodKey Actions
1. Registrationregister()Merge configurations, set up auth, configure file manager
2. Directory Setupinitial()Create directories, register commands, define publishables
3. Core Checkboot()Verify GP247 Core is active
4. Resource Loadingboot()Load helpers, register middleware, load views
5. Integrationboot()Share models, add UI modules, extend validation

The service provider uses defensive programming with extensive error handling and conditional initialization to ensure graceful degradation when dependencies are unavailable. All shop functionality is namespaced and isolated, allowing it to be added to or removed from the GP247 ecosystem without affecting other packages.

Sources: src/ShopServiceProvider.php1-296