Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Employee Laravel Package

aescarcha/employee

Symfony bundle providing REST endpoints for employee management. Integrates with FOSRestBundle, FOSUserBundle, JMS Serializer, NelmioApiDoc, Doctrine extensions, Fractal, plus Aescarcha Business and User bundles. Install via Composer and enable routes/config.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Run the core package and its dependencies in a single command:

    composer require aescarcha/employee "~1" friendsofsymfony/rest-bundle jms/serializer-bundle nelmio/api-doc-bundle friendsofsymfony/user-bundle aescarcha/user-bundle:dev-master league/fractal stof/doctrine-extensions-bundle aescarcha/business "~1"
    
  2. Enable Bundles Register the required bundles in config/bundles.php (Symfony 4+) or app/AppKernel.php (Symfony 3):

    // config/bundles.php
    return [
        // ...
        Stof\DoctrineExtensionsBundle\StofDoctrineExtensionsBundle::class => ['all' => true],
        FOS\RestBundle\FOSRestBundle::class => ['all' => true],
        FOS\UserBundle\FOSUserBundle::class => ['all' => true],
        JMS\SerializerBundle\JMSSerializerBundle::class => ['all' => true],
        Nelmio\ApiDocBundle\NelmioApiDocBundle::class => ['all' => true],
        Aescarcha\EmployeeBundle\AescarchaEmployeeBundle::class => ['all' => true],
        Aescarcha\BusinessBundle\AescarchaBusinessBundle::class => ['all' => true],
    ];
    
  3. Database Setup Run migrations (if provided) or manually create tables for:

    • Employee entity (likely tied to User via FOSUserBundle).
    • Business-related tables (e.g., Business, Department).
  4. First Use Case Create an employee via API or admin panel:

    # Example API endpoint (check Nelmio API docs after setup)
    POST /api/employees
    {
        "email": "employee@example.com",
        "password": "securepassword",
        "businessId": 1,
        "role": "manager"
    }
    

Implementation Patterns

Core Workflows

  1. Employee Management

    • CRUD via API: Leverage FOSRestBundle to expose endpoints for Employee entities. Example controller extension:
      use Aescarcha\EmployeeBundle\Entity\Employee;
      use FOS\RestBundle\Controller\Annotations as Rest;
      
      class EmployeeController extends AbstractController
      {
          /**
           * @Rest\Get("/employees/{id}")
           */
          public function getEmployee(Employee $employee): Employee
          {
              return $this->handleView($this->view($employee));
          }
      }
      
    • Serialization: Use JMS\Serializer or League\Fractal to customize API responses. Example Fractal transformer:
      namespace App\Transformer;
      
      use Aescarcha\EmployeeBundle\Entity\Employee;
      use League\Fractal\TransformerAbstract;
      
      class EmployeeTransformer extends TransformerAbstract
      {
          public function transform(Employee $employee)
          {
              return [
                  'id' => $employee->getId(),
                  'email' => $employee->getEmail(),
                  'business' => $employee->getBusiness()->getName(),
                  'createdAt' => $employee->getCreatedAt()->format('Y-m-d'),
              ];
          }
      }
      
  2. Business-Employee Relationships

    • Hierarchy: Use stof/doctrine-extensions for tree behavior (e.g., departments). Example entity:
      use Gedmo\Mapping\Annotation as Gedmo;
      
      /**
       * @Gedmo\Tree(type="nested")
       */
      class Department {}
      
    • Policy Enforcement: Validate employee-business assignments in a listener:
      use Aescarcha\EmployeeBundle\Entity\Employee;
      use Doctrine\Common\EventSubscriber;
      
      class EmployeeSubscriber implements EventSubscriber
      {
          public function getSubscribedEvents()
          {
              return ['prePersist', 'preUpdate'];
          }
      
          public function prePersist(Employee $employee)
          {
              if (!$employee->getBusiness()->isActive()) {
                  throw new \RuntimeException('Business must be active.');
              }
          }
      }
      
  3. API Documentation

    • Auto-generate Swagger docs via NelmioApiDocBundle.
    • Annotate controllers:
      /**
       * @Rest\Post("/employees", name="create_employee")
       * @Nelmio\ApiDoc\ApiDoc(
       *     description="Create a new employee",
       *     requirements={
       *         {"name"="email", "dataType"="string", "required"=true}
       *     }
       * )
       */
      

Integration Tips

  • Authentication: Integrate with FOSUserBundle for login/registration:
    # config/packages/fos_user.yaml
    fos_user:
        db_driver: orm
        user_class: Aescarcha\UserBundle\Entity\User
    
  • Event-Driven: Extend with custom events (e.g., EmployeeCreatedEvent):
    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    
    class EmployeeEventSubscriber implements EventSubscriberInterface
    {
        public static function getSubscribedEvents()
        {
            return [
                'employee.created' => 'onEmployeeCreated',
            ];
        }
    
        public function onEmployeeCreated(EmployeeCreatedEvent $event)
        {
            // Send welcome email, log activity, etc.
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Bundle Dependency Hell

    • Issue: aescarcha/user-bundle is on dev-master. Pin to a stable version or fork.
    • Fix: Use composer require aescarcha/user-bundle@dev-stable or replace with lexik/jwt-authentication-bundle if JWT is needed.
  2. Missing Migrations

    • Issue: No migration files provided. Manual SQL or doctrine:migrations:diff required.
    • Fix: Generate migrations after installation:
      php bin/console doctrine:migrations:diff
      php bin/console doctrine:migrations:migrate
      
  3. Serialization Conflicts

    • Issue: JMS\Serializer and League\Fractal may conflict if not configured.
    • Fix: Explicitly configure one serializer in config/packages/jms_serializer.yaml:
      jms_serializer:
          handlers:
              datetime: false # Disable if using Fractal
      
  4. API Doc Routes

    • Issue: NelmioApiDocBundle may not auto-discover routes if controllers lack annotations.
    • Fix: Manually add routes to nelmio_api_doc.yaml:
      nelmio_api_doc:
          routes:
              - name: "Employee API"
                path: "/api/doc.json"
      

Debugging

  • Doctrine Events: Enable logging for EmployeeSubscriber:
    # config/packages/monolog.yaml
    monolog:
        handlers:
            doctrine:
                type: stream
                path: "%kernel.logs_dir%/doctrine.log"
                level: debug
                channels: ["doctrine"]
    
  • API Responses: Use FOSRestBundle's dump() helper in controllers:
    $this->dump($employee); // Outputs raw data for debugging
    

Extension Points

  1. Custom Fields

    • Extend Employee entity:
      use Aescarcha\EmployeeBundle\Entity\Employee as BaseEmployee;
      
      class Employee extends BaseEmployee
      {
          /**
           * @ORM\Column(type="string", nullable=true)
           */
          private $customField;
      }
      
    • Update serializers/transformers accordingly.
  2. Business Logic

    • Override Aescarcha\BusinessBundle\Service\BusinessService:
      namespace App\Service;
      
      use Aescarcha\BusinessBundle\Service\BusinessService as BaseService;
      
      class BusinessService extends BaseService
      {
          public function validateEmployeeAssignment($employee, $business)
          {
              // Custom validation
          }
      }
      
    • Register as a decorator in config/services.yaml:
      services:
          App\Service\BusinessService:
              decorates: 'aescarcha.business.service.business'
              arguments: ['@App\Service\BusinessService.inner']
      
  3. Testing

    • Use nelmio/api-test-bundle for API testing:
      composer require --dev nelmio/api-test-bundle
      
    • Example test:
      use Nelmio\ApiTestBundle\JsonAssertionsTrait;
      
      class EmployeeTest extends WebTestCase
      {
          use JsonAssertionsTrait;
      
          public function testCreateEmployee()
          {
              $client = static::createClient();
              $client->request('POST', '/api/employees', [
                  'json' => ['email' => 'test@example.com']
              ]);
      
              $this->assertJsonValidation($client->getResponse());
          }
      }
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui