Structure Project Sample
- PHP: 8.3
- Laravel: 11.31
- MYSQL 8.0
- OS: Macos, Linux
- Sail (Docker) 8.2
- UI: Vite, Tailwind
- Filament: 3.0 (Admin Panel)
git clone git@github.com:TOMOSIA-VIETNAM/winner_scout.git
cd winner_scout
cp .env.example .env
docker run --rm -u "$(id -u):$(id -g)" -v "$(pwd):/var/www/html" -w /var/www/html laravelsail/php82-composer:latest composer install --ignore-platform-reqs
sudo vim ~/.zshrc
Add this alias to ~/.zshrc
file
alias sail='sh $([ -f sail ] && echo sail || echo vendor/bin/sail)'
sudo vim /etc/hosts
Add this line to hosts file
127.0.0.1 winner_scout.loc
sail up -d
sail composer install
sail composer dump-autoload
sail artisan key:generate
sail artisan optimize
sail artisan migrate
sail artisan db:seed
sail artisan storage:link
Document api for scramble
Url document local: http://template-laravel-module.loc/api-docs
sail npm install
sail npm run dev
sail npm run build
sail pint --test
sail pint -v
Create a feature
branch from the develop
branch
β
Development (during the process, if there is a topic regarding the source code, etc.)
β
Create a pull request from feature
branch to develop
branch
β
Review
β
Merge into develop
on GitHub
β
Release main
branch to production
<type>/<issue_number><issue_name>
- Example:
- feature/issue-352-payment-api - bugfix/issue-352-bug-payment - release/v2.1-release-payment-api
<type>: <description>
- Example:
- feat: Implement Admin UI dashboard - refactor: Admin UI dashboard - fix: Bug validation email when user register - revert: Revert commit
Dα»± Γ‘n Laravel vα»i kiαΊΏn trΓΊc modular hiα»n ΔαΊ‘i, tΓ‘ch biα»t rΓ΅ rΓ ng giα»―a core containers vΓ feature modules. Sα» dα»₯ng cΓ‘c pattern nhΖ° Actions, Repositories, DTOs, Events, vΓ Resources Δα» ΔαΊ£m bαΊ£o tΓnh maintainable vΓ scalable.
app/
βββ Containers/ # Core business logic containers
β βββ User/ # User domain
β βββ Blog/ # Blog domain
βββ Core/ # Shared core components
β βββ Actions/ # Base action classes
β βββ Repositories/ # Base repository classes
β βββ Services/ # Shared services
βββ Models/ # Global models
βββ Providers/ # Application providers
βββ Http/ # HTTP layer
modules/ # Feature modules
βββ Admin/ # Admin interface module (Filament)
βββ Api/ # API module (RESTful endpoints)
Vα» trΓ: app/Containers/User/
Chα»©c nΔng: QuαΊ£n lΓ½ domain User vα»i ΔαΊ§y Δα»§ business logic
CαΊ₯u trΓΊc:
User/
βββ Actions/ # Business logic actions
β βββ CreateUserAction.php
β βββ UpdateUserAction.php
β βββ DeleteUserAction.php
β βββ GetUserByIdAction.php
β βββ GetUsersAction.php
β βββ UploadAvatarAction.php
β βββ DeleteAvatarAction.php
βββ Data/
β βββ DTOs/ # Data Transfer Objects
β βββ CreateUserDTO.php
β βββ UpdateUserDTO.php
β βββ UploadAvatarDTO.php
βββ Events/ # Domain events
β βββ UserCreated.php
β βββ UserUpdated.php
β βββ UserDeleted.php
βββ Listeners/ # Event listeners
βββ Models/
β βββ User.php # Eloquent model
βββ Repositories/
β βββ IUserRepository.php # Interface
β βββ UserRepository.php # Implementation
βββ Validators/ # Custom validators
βββ UserValidator.php
Vα» trΓ: app/Containers/Blog/
Chα»©c nΔng: QuαΊ£n lΓ½ domain Blog vα»i CRUD operations
CαΊ₯u trΓΊc:
Blog/
βββ Actions/
β βββ CreateBlogAction.php
β βββ UpdateBlogAction.php
β βββ DeleteBlogAction.php
β βββ GetBlogByIdAction.php
β βββ GetBlogsAction.php
βββ Data/
β βββ DTOs/
β β βββ CreateBlogDTO.php
β β βββ UpdateBlogDTO.php
β βββ ValueObjects/
βββ Events/
β βββ BlogCreated.php
β βββ BlogUpdated.php
β βββ BlogDeleted.php
βββ Listeners/
βββ Models/
β βββ Blog.php
βββ Repositories/
βββ IBlogRepository.php
βββ BlogRepository.php
Vα» trΓ: app/Core/Actions/BaseAction.php
Chα»©c nΔng: Abstract base class cho tαΊ₯t cαΊ£ Actions
- Cung cαΊ₯p common methods
- Dependency injection container
- Error handling patterns
Vα» trΓ: app/Core/Repositories/BaseRepository.php
Chα»©c nΔng: Abstract base class cho tαΊ₯t cαΊ£ Repositories
- Common CRUD operations
- Pagination support
- Query building utilities
Vα» trΓ: app/Core/Services/
Chα»©c nΔng:
FileUploadService.php
: File upload logic- Shared utilities vΓ helpers
Vα» trΓ: app/Containers/{Container}/Data/DTOs/
Chα»©c nΔng:
- Validate vΓ transform input data
- Ensure data consistency
- Type safety
VΓ dα»₯:
class CreateUserDTO
{
public function __construct(
public string $name,
public string $email,
public string $role = 'user',
public string $status = 'active'
) {}
public static function fromRequest(Request $request): self
{
return new self(
name: $request->input('name'),
email: $request->input('email'),
role: $request->input('role', 'user'),
status: $request->input('status', 'active')
);
}
public function rules(): array
{
return [
'name' => 'required|string|max:255',
'email' => 'required|email|unique:users,email',
'role' => 'in:user,manager,admin',
'status' => 'in:active,inactive'
];
}
}
Vα» trΓ: modules/Admin/
Chα»©c nΔng: Web interface cho administrators
CαΊ₯u trΓΊc:
modules/Admin/
βββ Filament/ # Filament components
β βββ Resources/
β β βββ AdminResource/
β β βββ Pages/
β β βββ Widgets/
β β βββ AdminResource.php # Resource admin
β βββ Pages/ # Custom pages
β βββ Widgets/ # Dashboard widgets
βββ Http/
β βββ Controllers/
β β βββ Controller.php # Base controller
β βββ Middleware/
β β βββ Authenticate.php # Admin authentication
β β βββ SetLocale.php # Language switching
β βββ Requests/ # Form requests
βββ lang/ # Multi-language files
β βββ en/
β βββ ja/
βββ Providers/
β βββ AdminServiceProvider.php # Main service provider
β βββ FilamentServiceProvider.php # Filament panel config
β βββ RouteServiceProvider.php # Routes configuration
βββ resources/
β βββ assets/ # Frontend assets
β βββ views/ # Blade templates
βββ routes/
β βββ web.php # Web routes
TΓnh nΔng:
- Dashboard vα»i thα»ng kΓͺ real-time
- User management (CRUD, avatar upload)
- Blog management (CRUD, status management)
- Modern UI vα»i Bootstrap 5 vΓ Font Awesome
- Responsive design vα»i gradient themes
Vα» trΓ: modules/Api/
Chα»©c nΔng: RESTful API endpoints
CαΊ₯u trΓΊc:
Api/
βββ Http/
β βββ Controllers/
β β βββ ApiController.php
β β βββ UserController.php
β β βββ UserAvatarController.php
β β βββ AuthController.php
β β βββ Controller.php
β βββ Resources/
β β βββ UserResource.php
β βββ Requests/
βββ Providers/
β βββ ApiServiceProvider.php
β βββ RouteServiceProvider.php
β βββ ValidationProvider.php
βββ resources/
βββ routes/
β βββ api.php
βββ Transforms/
β βββ UserTransform.php
βββ Traits/
TΓnh nΔng:
- RESTful API endpoints
- JSON responses vα»i proper formatting
- Pagination support
- Error handling
- Resource transformation
- Response transformation vα»i Transforms
Thay thαΊΏ traditional Service layer bαΊ±ng Actions:
Ζ―u Δiα»m:
- Single responsibility principle
- Easy testing
- Clear business logic separation
- Dependency injection friendly
VΓ dα»₯:
class CreateUserAction extends BaseAction
{
public function __construct(
private IUserRepository $userRepository,
private UserValidator $validator
) {}
public function execute(CreateUserDTO $dto): User
{
// Validate input
$this->validator->validate($dto->toArray());
// Business logic
$user = $this->userRepository->create($dto->toArray());
// Dispatch events
event(new UserCreated($user));
return $user;
}
}
Interface: IUserRepository
Implementation: UserRepository
Chα»©c nΔng:
- Data access abstraction
- Query optimization
- Caching support
- Database agnostic
Chα»©c nΔng:
- File upload vα»i validation
- Image processing
- Storage management
- URL generation
Implementation:
FileUploadService
trong Core containerUploadAvatarAction
trong User container- Admin vΓ API endpoints vα»i dedicated controllers
Chα»©c nΔng:
- Full CRUD operations
- Status management (draft, published, archived)
- Slug generation
- Featured image support
Chα»©c nΔng:
- User statistics
- Role-based metrics
- Recent activity tracking
- Visual charts vΓ tables
Design System:
- Bootstrap 5 framework
- Font Awesome icons
- Custom CSS variables
- Gradient themes (Cyan/Blue-green)
- Responsive design
- Smooth animations
- Framework: Laravel 10+
- Database: SQLite (development), MySQL/PostgreSQL (production)
- Architecture: Modular with Domain-Driven Design
- Patterns: Repository, Action, DTO, Event
- CSS Framework: Bootstrap 5.3.2
- Icons: Font Awesome 6.4.2
- Fonts: Google Fonts (Inter)
- Styling: Custom CSS vα»i CSS Variables
- Package Manager: Composer
- Version Control: Git
- IDE Support: Laravel IDE Helper
- PHP 8.1+
- Composer
- SQLite (for development)
- Clone repository:
git clone <repository-url>
cd template-laravel-module
- Install dependencies:
composer install
- Environment setup:
cp .env.example .env
php artisan key:generate
- Database setup:
php artisan migrate
php artisan db:seed
- Storage setup:
php artisan storage:link
- Start development server:
php artisan serve
DB_CONNECTION=sqlite
DB_DATABASE=/absolute/path/to/database.sqlite
FILESYSTEM_DISK=public
βββ app/
β βββ Containers/
β β βββ User/
β β β βββ Actions/
β β β βββ Data/
β β β β βββ DTOs/
β β β βββ Events/
β β β βββ Listeners/
β β β βββ Models/
β β β βββ Repositories/
β β β βββ Validators/
β β βββ Blog/
β β βββ Actions/
β β βββ Data/
β β β βββ DTOs/
β β β βββ ValueObjects/
β β βββ Events/
β β βββ Listeners/
β β βββ Models/
β β βββ Repositories/
β βββ Core/
β β βββ Actions/
β β βββ Repositories/
β β βββ Services/
β βββ Models/
β βββ Providers/
β βββ Http/
βββ modules/
β βββ Admin/
β β βββ Filament/
β β βββ Http/
β β β βββ Controllers/
β β β βββ Middleware/
β β β βββ Requests/
β β βββ Providers/
β β βββ resources/
β β β βββ Views/
β β βββ routes/
β β βββ View/
β βββ Api/
β βββ Http/
β β βββ Controllers/
β β βββ Resources/
β β βββ Requests/
β βββ Providers/
β βββ resources/
β βββ routes/
β βββ Transforms/
β βββ Traits/
βββ database/
β βββ migrations/
β βββ seeders/
βββ public/
βββ routes/
βββ storage/
βββ config/
AppServiceProvider
: Main application providerRouteServiceProvider
: Route configuration
UserServiceProvider
: User container bindingsBlogServiceProvider
: Blog container bindings
AdminServiceProvider
: Admin module configurationApiServiceProvider
: API module configurationValidationProvider
: Custom validation rulesViewServiceProvider
: View configuration
Dα»± Γ‘n sα» dα»₯ng PHPUnit Δα» testing vα»i coverage ΔαΊ§y Δα»§ cho cαΊ£ unit tests vΓ feature tests. TαΊ₯t cαΊ£ tests ΔΓ£ Δược viαΊΏt vΓ pass thΓ nh cΓ΄ng.
- Tα»ng sα» tests: 16 tests
- Tests passed: 16 β
- Tests failed: 0 β
- Tα»ng sα» assertions: 110
- Test coverage: Unit tests + Feature tests
Vα» trΓ: tests/Unit/
Mα»₯c ΔΓch: Test cΓ‘c business logic components Δα»c lαΊp
tests/Unit/
βββ Actions/
β βββ GetUsersActionTest.php # Test GetUsersAction
βββ Repositories/
β βββ UserRepositoryTest.php # Test UserRepository
βββ DTOs/
β βββ CreateUserDTOTest.php # Test DTO validation
βββ ExampleTest.php # Basic unit test
Test Coverage:
- β Action execution vα»i filters
- β Pagination logic
- β Search functionality
- β Role filtering
- β Error handling
- β Default values
Vα» trΓ: tests/Feature/
Mα»₯c ΔΓch: Test API endpoints vΓ integration
tests/Feature/
βββ Api/
β βββ UserControllerTest.php # Test API endpoints
βββ Admin/
β βββ UserControllerTest.php # Test Admin interface
βββ ExampleTest.php # Basic feature test
Test Coverage:
- β API endpoints (GET, POST, PUT, DELETE)
- β Authentication vα»i Sanctum
- β JSON response structure
- β Pagination metadata
- β Search functionality
- β Filtering by role/department
- β Error handling
- β Validation errors
php artisan test
php artisan test --testsuite=Unit
php artisan test --testsuite=Feature
php artisan test tests/Unit/Actions/GetUsersActionTest.php
php artisan test --filter test_can_get_users_with_pagination
php artisan test --coverage
php artisan test -v
File: phpunit.xml
<testsuites>
<testsuite name="Unit">
<directory suffix="Test.php">./tests/Unit</directory>
</testsuite>
<testsuite name="Feature">
<directory suffix="Test.php">./tests/Feature</directory>
</testsuite>
</testsuites>
- Database: SQLite in-memory cho tests
- Authentication: Laravel Sanctum
- Factories: UserFactory vα»i realistic data
- Seeders: Test data generation
// Unit tests
public function test_can_get_users_with_pagination()
public function test_returns_empty_paginator_when_no_users()
public function test_uses_default_per_page_when_not_specified()
// Feature tests
public function test_can_get_users_list()
public function test_can_search_users_by_name()
public function test_returns_correct_user_data_structure()
public function test_example()
{
// Arrange - Setup test data
$user = User::factory()->create();
// Act - Execute the action
$response = $this->getJson('/api/v1/users');
// Assert - Verify results
$response->assertStatus(200);
}
// Mock repositories for unit tests
$this->mockRepository
->shouldReceive('findWithFilters')
->with(['role' => 'admin'], 10)
->once()
->andReturn($expectedPaginator);
use RefreshDatabase; // Reset database for each test
use WithFaker; // Generate fake data
File: database/factories/UserFactory.php
class UserFactory extends Factory
{
public function definition(): array
{
return [
'name' => fake()->name(),
'email' => fake()->unique()->safeEmail(),
'role' => fake()->randomElement(['user', 'manager', 'admin']),
'status' => fake()->randomElement(['active', 'inactive']),
'department' => fake()->optional()->jobTitle(),
];
}
public function admin(): static
{
return $this->state(fn (array $attributes) => [
'role' => 'admin',
]);
}
}
File: database/seeders/UserSeeder.php
class UserSeeder extends Seeder
{
public function run(): void
{
// Create test users with specific roles
User::create([
'name' => 'Admin User',
'email' => 'admin@admin.com',
'password' => Hash::make('password'),
'role' => 'admin',
'status' => 'active',
]);
}
}
public function test_optimized_user_query()
{
DB::enableQueryLog();
$users = User::with(['permissions', 'activities'])->get();
$this->assertLessThan(5, count(DB::getQueryLog()));
}
public function test_memory_efficient_pagination()
{
$memoryBefore = memory_get_usage();
User::paginate(1000);
$memoryAfter = memory_get_usage();
$memoryUsed = $memoryAfter - $memoryBefore;
$this->assertLessThan(10 * 1024 * 1024, $memoryUsed); // 10MB limit
}
- Laravel Telescope (development)
- Error tracking
- Performance monitoring
- Structured logging
- Error logging
- Access logging
- PSR-12 coding standards
- Laravel conventions
- Type hints vΓ return types
- PHPDoc comments
- Feature branches
- Pull request reviews
- Semantic commit messages
GET /api/users # List users
POST /api/users # Create user
GET /api/users/{id} # Get user
PUT /api/users/{id} # Update user
DELETE /api/users/{id} # Delete user
POST /api/users/{id}/avatar # Upload avatar
DELETE /api/users/{id}/avatar # Delete avatar
GET /api/blogs # List blogs
POST /api/blogs # Create blog
GET /api/blogs/{id} # Get blog
PUT /api/blogs/{id} # Update blog
DELETE /api/blogs/{id} # Delete blog
- Primary: Cyan (#00d2ff)
- Secondary: Blue (#3a7bd5)
- Success: Teal (#0fb9b1)
- Warning: Yellow (#f7b731)
- Danger: Red (#eb4d4b)
- Font Family: Inter
- Weights: 300, 400, 500, 600, 700
- Responsive: Mobile-first approach
- Cards: Rounded corners, shadows
- Buttons: Gradient backgrounds
- Tables: Clean headers, hover effects
- Forms: Focus states, validation
- Real-time notifications
- Advanced search & filtering
- Export functionality
- Multi-language support
- Advanced analytics
- API rate limiting
- Webhook system
- GraphQL API
- Microservices architecture
- Docker containerization
- CI/CD pipeline
- Automated testing
- Performance optimization
- Inline code documentation
- API documentation
- User guides
- Developer guides
- Issue tracking
- Feature requests
- Bug reports
- Technical support