--- title: "ConfigProvider - Bootstrap Modern PHP Applications" description: "An overview of the ConfigProvider pattern used in Laminas/Mezzio-based applications, including Dotkernel, to bootstrap middleware pipelines and dependency injection." author: "Florin Bidirean" date_published: "2025-08-20" canonical_url: "https://www.dotkernel.com/architecture/configprovider-bootstrap-modern-php-applications/" category: "Architecture" language: "en" --- # ConfigProvider - Bootstrap Modern PHP Applications ## TL;DR In PHP, a `ConfigProvider` is a class or callable that is part of an application's bootstrap process, returning configuration data that tells the platform which middleware should run, in what order, and under what conditions. Frameworks like Mezzio, Laminas, Slim, and the Dotkernel Headless Platform use ConfigProviders to declare middleware pipeline configuration, dependency injection mappings, and request handlers, which get merged together automatically during bootstrap (except in Dotkernel, where new ConfigProviders must be registered manually). ## Where Is the ConfigProvider Used? Mezzio (formerly Zend Expressive), Laminas, Slim, the Dotkernel Headless Platform, and other middleware-based frameworks often have a `ConfigProvider` class. In Laminas/Mezzio specifically, each module or package may contain a `ConfigProvider` that returns: - Middleware pipeline configuration: - Middleware classes or service names. - Error-handling middleware, which should have the lowest priority. - Middleware groups or nested arrays. - Dependency injection mappings. - Request Handlers. Example structure used in Dotkernel: ```php class ConfigProvider { public function __invoke(): array { return [ 'dependencies' => $this->getDependencies(), 'templates' => $this->getTemplates(), ]; } public function getDependencies(): array { return [ 'factories' => [ /* ... */ ], 'invokables' => [ /* ... */ ], ]; } public function getTemplates(): array { return [ 'paths' => [ /* ... */ ], 'error' => [ /* ... */ ], ]; } } ``` What each item means: | Item | Meaning | |---|---| | `dependencies` | Used by the dependency injector (e.g. [laminas-servicemanager](https://docs.mezzio.dev/mezzio/v3/features/container/laminas-servicemanager/)) to construct every requested service. | | `factories` | The factory builds the service. | | `invokables` | The service is built with `new` directly. | | `aliases` | Redirects to another service name. | | `delegators` | Wraps the original service. | | `templates` | Defines the paths for the template files. | ## How the ConfigProvider Works The ConfigProvider is automatically picked up by the framework during application bootstrap: 1. **Merge the global configuration** - All ConfigProviders are merged into one array. 2. **Read the configuration array** - A call similar to `$config = $container->get('config') ?? [];` reads an array of entries. 3. **Resolve item** - `$app->pipe()` is called to resolve one of the following: resolve the service name from the container, wrap the middleware if an array is provided, or call the closure or invokable object. 4. **Handle errors** - The error-handling middleware is the last one in the pipeline, to make sure it can handle any exceptions. 5. **Execute at runtime** - [Laminas Stratigility](https://docs.laminas.dev/laminas-stratigility/) iterates over the pipeline in the order it was registered. Each middleware can handle the request and return a response, or delegate execution to the next middleware in the pipeline, until a `ResponseInterface` is returned to the client. Below you can see how Mezzio and Dotkernel merge and use ConfigProviders to build the middleware pipeline and dependencies. ![](/uploads/article/ConfigProvider2.png) ## Benefits - **Centralized setup** - Instead of hardcoding bootstrap code, it's declared in a config provider so it's easy to read, change, or extend. - **Modular** - Each package can ship with its own config without interfering with others. - **Container-friendly** - Works well with frameworks using DI containers like Laminas ServiceManager, PHP-DI, or Pimple. - **Standardized service definitions** - Consistent rules for object creation, separate from business logic. - **Auto-Discovery** - In Laminas/Mezzio, the [ConfigAggregator](https://docs.laminas.dev/laminas-config-aggregator/) automatically loads and merges all ConfigProviders. Dotkernel is an exception: new ConfigProviders have to be added manually in `config/config.php`, because all the initial ConfigProviders required to install the applications are already injected. - **Environment-agnostic** - Returns an array that defines dev, test, or prod environments. - **Testability** - The consistent, central configuration promotes isolated (e.g. per-module) testing, easier swapping of dependencies, and assertion of pipeline setup (e.g. checking if a config key is present). ## Resources - [Mezzio Container](https://docs.mezzio.dev/mezzio/v3/features/container/config/) - [Laminas Config Aggregator](https://docs.laminas.dev/laminas-config-aggregator/config-providers/) - [PSR-15 (HTTP Server Request Handlers)](https://www.php-fig.org/psr/psr-15/) --- title: "Request Lifecycle for a Mezzio-Based Application" description: "A step-by-step walkthrough of how Dotkernel Light, a Mezzio-based application, handles an HTTP request from bootstrap through to the emitted response." author: "Florin Bidirean" date_published: "2026-05-26" canonical_url: "https://www.dotkernel.com/architecture/request-lifecycle-for-a-mezzio-based-application/" category: "Architecture" language: "en" --- # Request Lifecycle for a Mezzio-Based Application ## TL;DR The request lifecycle is the sequence of steps that happen from the moment a user makes an HTTP request until the server sends back a response. This is illustrated using Dotkernel Light, one of the applications in the Dotkernel Headless Platform suite, walking through entry point setup, routing, handler execution, template rendering, response creation, and the response emitter. ## The Request Lifecycle, Step by Step ### Entry Point 1. **HTTP Request** - Bootstrap the application, load configuration and create the Mezzio application instance. 2. **Service Container** - Register factories, aliases and delegators. All services are configured and ready to use. 3. **Route Registration** - Read all available routes with their allowed request methods and dynamically register them in the application. Routes are managed by FastRoute. Example: `/page/about` -> `GetPageViewHandler`, Method: `GET`, Route name: `page::about`. 4. **Middleware Pipeline** - Loads the predefined order of middleware. It defines how incoming HTTP requests move through the application and how responses are generated. ### Processing 5. **Routing** - FastRoute matches the URL and method against registered routes. Match: `GET /page/about`, Handler: `GetPageViewHandler`, Route name: `page::about`. 6. **Handler Invocation** - Extract the matched route name from the request and pass it to the renderer: ```php $template = $request->getAttribute(RouteResult::class)->getMatchedRouteName(); // $template = 'page::about'; ``` 7. **Custom Logic Execution in Handler** - Execute the business logic in the handler. The process can involve services and any custom logic. 8. **Template Rendering** - Twig loads the template, applies the layout, renders blocks and includes partials. Load: `src/Page/templates/page/about.html.twig`, Extends: `@layout/default.html.twig`, Render blocks: `title`, `content`, Include partials: `alerts.html.twig`, etc., Output: Final HTML. 9. **Response Creation** - An `HtmlResponse` is created with status, headers and the rendered HTML body. Status: `200 OK`, Content-Type: `text/html; charset=utf-8`, Body: Rendered HTML. 10. **Response Pipeline** - The response flows back through the middleware stack. Middleware can modify headers, cookies, compress content, etc. ### Exit Point 11. **Response Emitter** - The final response is sent back to the browser. The page is rendered and sent to the user, as one of `HTTP 20x/30x`, `HTTP 40x`, or `HTTP 50x`. ## Resources - [Dotkernel Light on GitHub](https://github.com/dotkernel/light) - [Dotkernel Light documentation](https://docs.dotkernel.org/light-documentation/) - [Dotkernel Headless Platform suite on GitHub](https://github.com/dotkernel) --- title: "Understanding Middleware" description: "An introduction to middleware in PHP web applications: what it is, what it's used for, how PSR-15 defines it, and how it's called within an application's pipeline." author: "Florin Bidirean" date_published: "2025-05-22" canonical_url: "https://www.dotkernel.com/architecture/understanding-middleware/" category: "Architecture" language: "en" --- # Understanding Middleware ## TL;DR Middleware is code that exists between the request and response: it can take an incoming request, act on it, and either complete the response itself or delegate to the next middleware in the queue. It's used for concerns like authentication, CORS, caching, rate limiting, and more, and in PHP a PSR-15 compliant middleware implements `Psr\Http\Server\MiddlewareInterface` with a single `process()` method. ## The Purpose of Middleware Middleware makes it easier for software developers to implement communication and input/output, so they can focus on the specific purpose of their application. In web services, the `Input` represents the `Request` received, and `Output` represents the `Response` to be sent. ## Using Middleware Middleware can be used for purposes such as, but not limited to: - A/B Testing - Debugging - Caching - CORS - Authentication (HTTP Basic Auth, OAuth 2.0, OpenID) - CSRF Protection - Rate Limiting - Referrals - IP Restriction ## Usage According to PSR-15: HTTP Server Request Handlers, a component that processes an incoming request and generates a response is a middleware. To be compliant with the PSR-15 standard, the middleware must implement `Psr\Http\Server\MiddlewareInterface`: ```php class MyMiddleware implements MiddlewareInterface ``` The middleware class must then implement the `process` method: ```php public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface; ``` Example implementation of a middleware which processes the request: ```php class ExampleMiddleware implements MiddlewareInterface { public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { //process request return $handler->handle($request); } } ``` Example implementation of a middleware which processes the response: ```php class ExampleMiddleware implements MiddlewareInterface { public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { $response = $handler->handle($request); //process response return $response; } } ``` An approach that processes both the request and response: ```php class ExampleMiddleware implements MiddlewareInterface { public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { //process request $response = $handler->handle($request); //process response return $response; } } ``` ## How Middleware Is Called The application pipeline defines the execution flow. The request passes through the middleware in the pipeline, one by one, in the order they are placed in the pipeline. Each middleware processes the request and/or response and either passes control to the next middleware in the chain or terminates the request and returns a response. - If control passes through all middleware successfully, execution is eventually passed to the custom code which generates a response of its own. Execution then passes through the middleware in reverse order and returns the response. - If execution is terminated before reaching the custom code (e.g. via an exception), the response is generated by the last middleware reached by the execution. ## Middleware in Practice A simple real world example of middleware usage is the enhancement of a request with the user IP for logging purposes or building reports based on geographical data. For this example the pipeline has a single middleware. The flow begins with a request. Execution passes control to the IP middleware, which enhances the request with the user's IP and other relevant data. Control passes to the custom handler that processes the request and returns a response. The flow continues in reverse order, back to the IP middleware, which can, if needed, change the output before it gets returned to the user that initiated the request. ## Resources - [Why Care About PHP Middleware?](https://philsturgeon.uk/php/2016/05/31/why-care-about-php-middleware/) - [Learn more about Mezzio from the source](https://docs.mezzio.dev/) - [Laminas components](https://docs.laminas.dev/components/) - [Dotkernel Light, an implementation of Mezzio using handlers](https://github.com/dotkernel/light) - [The Slim PHP micro framework](https://www.slimframework.com/) - [The PHP Framework Interop Group's full list of PSRs](https://www.php-fig.org/psr/) - [PSR-7: The magical middleware tour](https://vimeo.com/showcase/4061778/video/177154167) - [From Helpers to Middleware](https://www.youtube.com/watch?v=v1I57-_Rsv0) --- title: "Basic Security in Dotkernel Headless Platform" description: "A practical overview of software security practices implemented across the Dotkernel Headless Platform, covering input validation, content negotiation, CORS, RBAC, OAuth2, sessions, dependencies, and more." author: "Florin Bidirean" date_published: "2025-10-14" canonical_url: "https://www.dotkernel.com/best-practice/basic-security-in-dotkernel-headless-platform/" category: "Best Practice" language: "en" --- # Basic Security in Dotkernel Headless Platform ## TL;DR Software security should always be top of mind for a developer, since ignoring it can lead to major costs, data loss, GDPR fines, or the loss of client trust. The article surveys many facets of software security and walks through the practical measures Dotkernel Headless Platform takes for each: input validation, content negotiation, CORS, RBAC, demo credentials, error reporting, OpenAPI docs, PHP and JavaScript dependencies, OAuth2, session/cookie settings, and CI checks. **Software security** should always be in the back of your mind as a developer. It may seem fine at first to deliver a feature sooner, only to find later on that you left a backdoor into your crisp new update. You ignore security at your own risk, with potentially major costs to your personal or your organization's image, and to your client's trust in your abilities. The costs to recover the damages caused by a lacking security are sometimes astronomical, enough to put a company out of business. There are many facets of software security, meaning there are a lot of potential ways a hacker can access your code or your data fraudulently: - Authentication and access control. - Data protection. - Input validation and injection. - Web and API security. - Dependency and supply chain risks. - Configuration and deployment. - Network and infrastructure security. - Logging, monitoring and incident response. - Secure software development lifecycle. - Human and organizational factors. To keep a platform safe, you must actively mitigate these risks with recommended coding practices that include tight security. You wouldn't build a nice house, only to leave the door unlocked, right? ## The Tenets of Software Security in Dotkernel Headless Platform We at Dotkernel aim to: - Create code that follows software security guidelines. - Implement community recommendations related to software security. - Use 3rd-party code and libraries from trusted sources. - Constantly monitor software news related to security vulnerabilities and mitigate them as soon as possible. We do all this to attempt to stay ahead of the vulnerabilities that can lead from otherwise useful, productive code, to data loss and a GDPR fine, or a loss of funds for our clients. Let's take a practical view on software security in Dotkernel. ## Form Input Validation You should never trust that the user inputs correct data by passing it directly into your business logic. By defining the configuration for an input filter, you ensure that a field is both present, and of the correct type. [Dotkernel API](https://www.dotkernel.com/api/) makes use of [laminas/laminas-inputfilter](https://github.com/laminas/laminas-inputfilter) for this purpose. In addition to the above filtering, Dotkernel Admin also makes use of [laminas/laminas-form](https://github.com/laminas/laminas-form). laminas-form contains: - A thin layer of objects representing form elements. - An InputFilter for each input, like mentioned previously, or custom validators. - Methods for binding data to and from the form. laminas-form ensures that data validation, filtering, and rendering enforce strong security practices by design. It also has integration with the Laminas Security Ecosystem that contains laminas-escaper, laminas-validator, laminas-session, and laminas-filter. ## Content Negotiation Content negotiation is used in RESTful APIs to ensure that systems work seamlessly together by having the client and server agree on the format and language of data they exchange. Dotkernel API handles content negotiation via a middleware configured in the `config/autoload/content-negotiation.global.php` file. It handles client-side content negotiation via the use of two HTTP request headers: `Content-Type` and `Accept`, and returns `application/json`, `application/hal+json` data formats. ## Cross-Origin Resource Sharing Cross-Origin Resource Sharing (or CORS) is a security mechanism implemented into web browsers to control how web pages can request resources from a different domain than the one where the request originated from. In Dotkernel API, CORS is handled by [mezzio/mezzio-cors](https://github.com/mezzio/mezzio-cors) and configured in the `config/autoload/cors.local.php` file. mezzio-cors starts to detect the proper `cors` configuration whenever it detects a `cors preflight`. Cors validates the call using several configuration items: origins, headers, max age, credentials. > When configuring your pipeline, make sure to add the CorsMiddleware BEFORE the RouteMiddleware. ## Role-Based Access Control Role-Based Access Control (or RBAC) is a security model used in software systems to manage access to resources. It does this by assigning roles to user types which are in turn assigned to users who require a certain level of access. Dotkernel API uses [mezzio/mezzio-authorization-rbac](https://github.com/mezzio/mezzio-authorization-rbac) for this purpose. There are several roles predefined, which you can configure to suit your project by editing the `config/autoload/authorization.global.php` file. ## Demo Credentials Demo credentials are provided in Dotkernel API for your convenience, to allow you to test the installation easily. > It is important to **update or remove** these accounts in your production environment. ## Error Reporting Endpoint and ErrorReportingTokens The purpose for the error reporting endpoint is to have a reliable channel through which 3rd-party developers can report issues to you directly. Dotkernel API has a dedicated endpoint `/error-report` for this purpose. It uses an `ErrorReportingToken` set up in the configuration file `config/autoload/error-handling.global.php`. ## OpenAPI Documentation OpenAPI documentation (formerly known as Swagger) provides a standardized, machine-readable way to describe APIs, meaning their `requests` and `responses`. It's critical for: - Developer efficiency - it streamlines communication between front and back end developers, and it allows developers to use mock servers before the backend is fully implemented. - Reliability - documentation can be auto-generated, testing is easier. - Integration - several tools support OpenAPI, like Postman and Codegen libraries for multiple libraries. Dotkernel API implements [zircote/swagger-php](https://github.com/zircote/swagger-php) to provide an interactive documentation. > Do **not** include sensitive information for your endpoints. Do **not** enable documentation in a production environment. ## PHP Dependencies Modern PHP projects rely heavily on external packages via package managers like Composer. There is a tangible risk of exposing your application by using insecure dependencies. Dotkernel API has regular checks for vulnerable and outdated packages. Often the dependencies used in projects have transient dependencies which must also be checked. > Always use dependencies from reliable sources and keep them updated to their latest version. ## OAuth2 Security OAuth 2.0 is a secure authorization framework that allows one application to access resources or data on behalf of a user, without requiring the user's password. It is considered an industry standard for secure authorization across web, mobile, and API-based systems. Dotkernel API uses the [mezzio/mezzio-authentication-oauth2](https://github.com/mezzio/mezzio-authentication-oauth2) for the OAuth2 authentication service. The package itself is secure, but you still need to make sure you use it properly: - Replace or update the default `admin` and `frontend` clients on your production environment. - Update the `access` and `refresh` tokens to match your application's requirements. The defaults are one day for `access` and one month for `refresh`. - Make sure to **not** commit any local keys generated by `./vendor/bin/generate-oauth2-keys`. They are used to verify the transmitted JWTs. ## Session and Cookie Settings Sessions and cookies are used in web development to store data between HTTP requests. For example, they can be used to save login information or preferences, and to track user behavior. Dotkernel configures cookies in the `config/autoload/session.global.php` file. It contains several parameters that you must revise and adapt to your application: - session_config.cookie_httponly - session_config.cookie_samesite - session_config.cookie_secure ## JavaScript Dependencies Very much like `composer` for PHP, JavaScript has its own dependencies, usually installed via `npm` or `yarn`. The JavaScript ecosystem has recently been attacked by hackers who targeted several widely used npm packages that have a total number of uses in the billions. Dotkernel uses `npm` to handle JavaScript dependencies. We monitor the news to stay on top of these security issues and use npm packages from reliable sources. Even so, you should regularly use the `npm audit` to check for vulnerabilities among your installed npm libraries. ## Other Security Considerations All components of **Dotkernel Headless Platform** have several configuration files with the name format `*.global.php`, `*.php.dist` and `*.local.php`. You must **only** include sensitive information in the `*.local.php` files, since they are, by default, ignored by the VCS. The `development mode` is designed, as the name suggests, only for the development period. By enabling development mode, you enable features like debug mode, cache clear and show error details. These should be hidden from the production environment to avoid exposing sensitive data or code. The GitHub Action [Laminas Continuous Integration](https://github.com/laminas/laminas-continuous-integration-action) is an integral component of Dotkernel API. It ensures code quality by streamlining the execution of PHP quality assurance (QA) tasks within continuous integration (CI) workflows. Most often triggered by commits to the repository, it builds a matrix of tests: static analysis, coding standards checks, and unit tests. ## Resources - [Basic Security in Dotkernel Admin](https://docs.dotkernel.org/admin-documentation/v6/security/basic-security/) - [Basic Security in Dotkernel API](https://docs.dotkernel.org/api-documentation/v6/security/basic-security/) - [Content Negotiation in Dotkernel REST API](https://www.dotkernel.com/dotkernel-api/content-negotiation-in-dotkernel-rest-api/) - [laminas-form Documentation](https://docs.laminas.dev/laminas-form/v3/intro/) - [CORS in Dotkernel API](https://docs.dotkernel.org/api-documentation/v6/tutorials/cors/) - [CORS Policy Setup in Dotkernel](https://www.dotkernel.com/how-to/cors-policy-setup-in-dotkernel-using-mezzio-cors/) - [Error Reporting Endpoint](https://docs.dotkernel.org/api-documentation/v6/core-features/error-reporting/) - [OpenAPI Documentation](https://docs.dotkernel.org/api-documentation/v6/openapi/introduction/) - [mezzio/mezzio-authentication-oauth2 Configuration](https://docs.mezzio.dev/mezzio-authentication-oauth2/v1/intro/#configuration) --- title: "Dependency Injection vs. Factory Design Pattern" description: "Dotkernel's dot-dependency-injection package lets you wire a service with an #[Inject] attribute or a hand-written factory. This article compares both approaches with real dotkernel/api code and explains when each one fits." author: "Florin Bidirean" date_published: "2026-10-12" canonical_url: "https://www.dotkernel.com/best-practice/ai-native-coding-pods/" category: "Best Practice" language: "en" --- # Dependency Injection vs. Factory Design Pattern ## TL;DR Declarative dependency injection with an `#[Inject]` attribute removes one factory class per service and keeps dependencies next to the constructor they feed. The Factory design pattern, one hand-written creational class per service, keeps static type checking and full control over construction. Use `#[Inject]` for plain constructor wiring, apply the Factory pattern to computed, conditional, decorated, or third-party classes, and mix both freely in the same Mezzio application. ## Introduction **Dependency injection (DI)** means a class receives the objects it needs instead of building them, usually through its constructor, as Fabien Potencier explains in [What is Dependency Injection?](https://fabien.potencier.org/what-is-dependency-injection.html). You gain swappable implementations, easy mocking in tests, and classes that leave object creation to someone else. The **Factory design pattern** answers a different question: *who builds* an object, and where that construction code lives. On its own it is "pull" (the caller asks a factory), while DI is "push" (dependencies are handed in). In a [PSR-11](https://www.php-fig.org/psr/psr-11/) application, both meet in the container. PSR-11 only defines how entries are retrieved (`get()` and `has()`); the factories and delegators configuration below belongs to `ServiceManager`. PSR-11 also warns against passing the container into an object so it can fetch its own dependencies: the service locator anti-pattern. The classic approach applies the Factory pattern once per service, so every constructor change means editing two files. Dotkernel's [dot-dependency-injection](https://github.com/dotkernel/dot-dependency-injection) package takes a DI-first route: an `#[Inject]` attribute on the constructor plus one shared `AttributedServiceFactory` for every service ([introduction](https://www.dotkernel.com/dotkernel/dependency-injection-made-easy-in-laminas-mezzio-applications/), [documentation](https://docs.dotkernel.org/dot-dependency-injection/v1/attributes-vs-factories/)). Below, both are compared using real code from the [Dotkernel API](https://github.com/dotkernel/api). ## Comparison Table | Aspect | Factory design pattern (hand-written factory) | Dependency injection (`#[Inject]` attribute) | |---------------------------------|--------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------| | Where construction is described | In a dedicated factory class | Declared on the constructor itself | | How dependencies flow | The factory pulls from the container, then pushes into the constructor | The shared factory reads the attribute and pushes into the constructor | | Files per service | 2: the class and its factory | 1: the class | | Static type checking | Verified by your IDE and static analysis | None; identifiers are strings resolved at runtime, and PHP's type declarations catch a mismatch only when the service is built | | Argument order | Kept in sync manually, but verified statically in the `new` call (named arguments also possible) | Kept in sync manually; a mistake surfaces only at runtime | | Reflection | None when the service is built | One `ReflectionClass` per service creation (usually once per request, since services are shared by default) | | Conditional wiring | Fully supported | Not supported | | Third-party classes | Works on any class | Only classes you can annotate | | Config access | `$container->get('config')['user']` | `'config.user'` | | Error handling | Whatever you write | Uniform `Dot\DependencyInjection\Exception\ExceptionInterface` | | Doctrine repositories | A factory for each repository | `AttributedRepositoryFactory` | Rule of thumb: if the constructor only needs things the container already holds, let dependency injection do the work with the attribute. If construction needs logic, that logic deserves the Factory pattern. ## Code Examples from dotkernel/api ### A Service Wired with Dependency Injection `UserAvatarService` needs a Doctrine repository and the application config. In dotkernel/api, the class declares both on the constructor: ```php use Core\User\Repository\UserAvatarRepository; use Dot\DependencyInjection\Attribute\Inject; class UserAvatarService implements UserAvatarServiceInterface { /** * @param array $config */ #[Inject( UserAvatarRepository::class, 'config', )] public function __construct( protected UserAvatarRepository $userAvatarRepository, protected array $config, ) { } } ``` The only wiring left is one line in the module's `ConfigProvider`: ```php use Dot\DependencyInjection\Factory\AttributedServiceFactory; 'factories' => [ UserAvatarService::class => AttributedServiceFactory::class, ], ``` The same `AttributedServiceFactory` entry is repeated for every handler, service, and middleware in the module. Note that a factory is still involved, but it is one generic factory driven by metadata, not a per-class application of the pattern. The attribute lists the container identifiers in constructor order, which is the order you must keep in sync by hand. ### The Same Service with the Factory Design Pattern The factory below is illustrative: dotkernel/api does not ship it, but it is what the same wiring looks like when you apply the Factory pattern instead of the attribute. ```php use Core\User\Repository\UserAvatarRepository; use Psr\Container\ContainerInterface; class UserAvatarServiceFactory { public function __invoke(ContainerInterface $container): UserAvatarService { return new UserAvatarService( $container->get(UserAvatarRepository::class), $container->get('config'), ); } } ``` Its `ConfigProvider` entry points to the new class, not to the shared one: ```php 'factories' => [ UserAvatarService::class => UserAvatarServiceFactory::class, ], ``` That is two files instead of one, and a second place to edit whenever the constructor changes. In return, the `new UserAvatarService(...)` call is checked statically: a wrong argument type or order is caught by your IDE and static analysis before the code runs. With the attribute, the same mistake shows up when the service is built. Either way, `UserAvatarService` itself still receives its dependencies through the constructor; the pattern only changes where the assembly code lives. ### Doctrine Repositories Repositories are where declarative injection saves the most repetition. In dotkernel/api, the repository declares which entity it serves: ```php use Core\App\Repository\AbstractRepository; use Core\User\Entity\UserAvatar; use Dot\DependencyInjection\Attribute\Entity; #[Entity(name: UserAvatar::class)] class UserAvatarRepository extends AbstractRepository { } ``` The module `ConfigProvider` registers it with the dedicated factory: ```php use Dot\DependencyInjection\Factory\AttributedRepositoryFactory; 'factories' => [ UserAvatarRepository::class => AttributedRepositoryFactory::class, UserDetailRepository::class => AttributedRepositoryFactory::class, UserRepository::class => AttributedRepositoryFactory::class, ], ``` With the Factory pattern applied per class, each repository needs its own factory that fetches the entity manager and asks it for the right repository, the same boilerplate repeated per entity. ### Where the Factory Pattern Still Wins Some objects cannot be described by a list of container identifiers. `ErrorResponseGeneratorFactory` in dotkernel/api reads a config value, with a fallback when the container has no config at all: ```php class ErrorResponseGeneratorFactory { public function __invoke(ContainerInterface $container): ErrorResponseGenerator { $config = $container->has('config') ? $container->get('config') : []; assert(is_array($config)); return new ErrorResponseGenerator($config['debug'] ?? false); } } ``` Three things make this a job for the Factory pattern. `ErrorResponseGenerator` belongs to Mezzio, so you cannot annotate it. The `has()` check is conditional logic. The constructor receives a computed scalar, `$config['debug'] ?? false`, not something the container already holds. Encapsulating that kind of construction logic is exactly what the pattern exists for. `EntityListenerResolverFactory` is another case: it builds an `EntityListenerResolver` that receives the container itself. ```php class EntityListenerResolverFactory { public function __invoke(ContainerInterface $container): EntityListenerResolver { return new EntityListenerResolver($container); } } ``` An attribute cannot express "give me the container," and this resolver exists to look up Doctrine entity listeners on demand. That is a deliberate exception. It does not make the container a general-purpose dependency for your services. ### Using Both in One Project Dependency injection and the Factory pattern share the same `ConfigProvider`. dotkernel/api's `App` module, for example, wires its services with the attribute and still decorates selected services with delegators, which are factories you write: ```php 'delegators' => [ GetIndexResourceHandler::class => [HandlerDelegatorFactory::class], ProblemDetailsMiddleware::class => [ProblemDetailsDelegatorFactory::class], ], 'factories' => [ GetIndexResourceHandler::class => AttributedServiceFactory::class, ErrorReportService::class => AttributedServiceFactory::class, ], ``` A service can be built through attribute-driven injection and still be wrapped by a delegator. Which approach applies to which service is decided entirely by the configuration. ### The Anti-Pattern to Avoid Both approaches keep the container out of your classes. This is what PSR-11 warns against: ```php class UserAvatarService { public function __construct( protected ContainerInterface $container, ) { } public function deleteAvatar(User $user): void { $repository = $this->container->get(UserAvatarRepository::class); // ... } } ``` The dependencies are now hidden: the constructor signature no longer says what the class needs, and a missing service no longer fails when `UserAvatarService` is built, but only when `deleteAvatar()` is called. That may be a rarely used code path that slips past your tests and fails in production. Tests also have to build a container just to run one method. The same problem appears if the service calls a static factory such as `UserAvatarRepositoryFactory::create()` from inside its own methods: the Factory pattern belongs in the wiring, not inside the class it serves. Declare `UserAvatarRepository` in the constructor instead, using either approach from this article. ## Conclusion DI decides how a class receives its dependencies; the Factory pattern decides where its assembly code lives. Either way, your service gets the same constructor injection. Default to `#[Inject]` when a class only needs what the container already holds. Use the Factory pattern when construction needs logic or the class isn't yours to annotate. The `ConfigProvider` decides per service, so you can mix both. Learn more in the [dot-dependency-injection documentation](https://docs.dotkernel.org/dot-dependency-injection/v1/attributes-vs-factories/) and the [Dotkernel API](https://github.com/dotkernel/api) source. --- title: "htaccess 301 redirect non-www to www" description: "How to configure .htaccess RewriteCond/RewriteRule directives to redirect a non-www domain to its www version, or vice versa." author: "admin" date_published: "2011-03-14" canonical_url: "https://www.dotkernel.com/best-practice/htaccess-301-redirect-non-www-to-www/" category: "Best Practice" language: "en" --- # htaccess 301 redirect non-www to www To always redirect users to the www site (for example: https://dotboost.com to https://www.dotboost.com), add the following lines to .htaccess, right after **RewriteEngine On**: ```shell RewriteCond %{HTTP_HOST} ^dotboost.com RewriteRule ^(.*)$ http://www.dotboost.com/$1 [L,R=301] ``` If, on the other hand, you want to redirect https://www.dotboost.com to https://dotboost.com, add the following lines instead: ```shell RewriteCond %{HTTP_HOST} ^www.dotboost.com RewriteRule ^(.*)$ http://dotboost.com/$1 [L,R=301] ``` Replace dotboost.com with your site's domain. --- title: "INSERT, UPDATE, DELETE statements with Zend_Db" description: "How to write INSERT, UPDATE, and DELETE (DML) statements using Zend_Db, alongside their equivalent raw SQL." author: "Teo" date_published: "2010-06-16" canonical_url: "https://www.dotkernel.com/best-practice/insert-update-delete-statements-with-zend-db/" category: "Best Practice" language: "en" --- # INSERT, UPDATE, DELETE statements with Zend_Db ## TL;DR DML (Data Manipulation Language) statements change data values in database tables. This article, continuing the Zend_Db series, shows how the three primary DML statements - INSERT, UPDATE, and DELETE - are written in raw SQL and translated into Zend_Db method calls. Continuing the Zend_DB article [series](https://www.dotkernel.com/best-practice/sql-queries-using-zend-db-select/), we are stopping now at DML statements. DML (Data Manipulation Language) statements are statements that change data values in database tables. There are 3 primary DML statements: - INSERT - Inserting new rows into database tables. - UPDATE - Updating existing rows in database tables. - DELETE - Deleting existing rows from database tables. ```php $db = Zend_Db::factory('Pdo_Mysql', $dbConnect); ``` **INSERT** ```sql INSERT INTO user(email, password, firstName, lastName, active) VALUES ('$email', '$password', '$firstName', '$lastName', 1); ``` The above SQL *INSERT* statement is translated in Zend_Db as follows: ```php $data = array( 'email' => $email, 'password' => $password, 'firstName' => $firstName, 'lastName' => $lastName, 'active' => '1'); $db->insert('user', $data); ``` **UPDATE** ```sql UPDATE user SET password = '$password', firstName = '$firstName', lastName = '$lastName', accountUpdate = (accountUpdate +1) WHERE id = '$id' ``` The above SQL *UPDATE* statement is translated in Zend_Db as follows: ```php $data = array('password' => $password, 'firstName' => $firstName, 'lastName' => $vlastname, 'accountUpdate' => new Zend_Db_Expr('accountUpdate+1')); $db->update('user', $data, 'id = '.$id); ``` **DELETE** ```sql DELETE FROM user WHERE id = '$id' ``` The above SQL *DELETE* statement is translated in Zend_Db as follows: ```php $db->delete('user', 'id = '.$id); ``` ## Resources - [Zend_Db series](https://www.dotkernel.com/best-practice/sql-queries-using-zend-db-select/) --- title: "SQL queries using Zend_Db - SELECT" description: "How to write SELECT queries with JOINs and WHERE IN clauses using Zend_Db, alongside their equivalent raw SQL." author: "Teo" date_published: "2010-06-15" canonical_url: "https://www.dotkernel.com/best-practice/sql-queries-using-zend-db-select/" category: "Best Practice" language: "en" --- # SQL queries using Zend_Db - SELECT ## TL;DR Zend_Db and its related classes provide a simple SQL database interface for Zend Framework. This article shows how classical SELECT queries with JOINs and WHERE IN clauses are translated into Zend_Db's select() style, and how to debug the generated query. [Zend_Db](https://docs.laminas.dev/laminas-db/adapter/) and its related classes provide a simple SQL database interface for Zend Framework. To connect to MySQL database, we are using Pdo_Mysql adapter : ```php $db = Zend_Db::factory('Pdo_Mysql', $dbConnect); ``` **SELECT query - WHERE clause** The below 2 classical SQL queries are equivalent. First one is simple, the second one use INNER JOIN keyword, but the result is the same. ```sql SELECT a.id, a.name, b.order_id FROM users AS a, orders AS b WHERE a.id = b.user_id AND a.id = {$userId} ``` ```sql SELECT `a`.`id`, `a`.`name`, `b`.`order_id` FROM `users` AS `a` INNER JOIN `orders` AS `b` ON a.id = b.user_id WHERE (a.id = '{$userId}') ``` The above queries are translated in Zend_Db style: ```php $select = $db->select() ->from(array('a'=>'users'), array('a.id', 'a.name')) ->join(array('b'=>'orders'), 'a.id = b.user_id', array('b.order_id')) ->where('a.id = ?', $userId) ``` If we don't want to select any column from the second table, the 3rd parameter of join() method should be an empty string ```sql SELECT a.id, a.name FROM users AS a, orders AS b WHERE a.id = b.user_id AND a.id = {$userId} ``` ```php $select = $db->select() ->from(array('a'=>'users'), array('a.id', 'a.name')) ->join(array('b'=>'orders'), 'a.id = b.user_id', '') ->where('a.id = ?', $userId) ``` Note: If we don't write the 3rd parameter, it will select all the fields from that table: ```sql SELECT a.id, a.name, b.* FROM users AS a, orders AS b WHERE a.id = b.user_id AND a.id = {$user_id} ``` ```php $select = $db->select() ->from(array('a'=>'users'), array('a.id', 'a.name')) ->join(array('b'=>'orders'), 'a.id = b.user_id') ->where('a.id = ?', $userId) ``` **SELECT query - WHERE IN clause** ```sql SELECT id FROM users WHERE aff_id IN ('1','2','3') ``` ```php $select = $db->select() ->from('users', array('id')) ->where('aff_id IN (?)', array(1,2,3)); ``` **Note**: If you are not sure if you write the correct query, before you fetch it you can echo your query to visualize it: ```php echo $select->__toString();exit; ``` ## Resources - [Zend_Db](https://docs.laminas.dev/laminas-db/adapter/) - [What are returning the FETCH functions from Zend_Db](https://www.dotkernel.com/best-practice/what-are-returning-the-fetch-functions-from-zend-db/) - [Subqueries with Zend_Db](https://www.dotkernel.com/best-practice/subqueries-with-zend-db/) - [INSERT, UPDATE, DELETE statements with Zend_Db](https://www.dotkernel.com/best-practice/insert-update-delete-statements-with-zend-db/) --- title: "Subqueries with Zend_Db" description: "How to build a query combining COUNT, LEFT JOIN, and GROUP BY across multiple tables using Zend_Db, including a subquery embedded as a column." author: "Teo" date_published: "2010-06-15" canonical_url: "https://www.dotkernel.com/best-practice/subqueries-with-zend-db/" category: "Best Practice" language: "en" --- # Subqueries with Zend_Db ## TL;DR Continuing the Zend_Db series, this article shows a more complex query - combining COUNT(), LEFT JOIN, and GROUP BY across 3 tables, with a count taken from 2 different tables - and how to build it, including a nested subquery, using Zend_Db. Continuing the Zend_DB article [series](https://www.dotkernel.com/best-practice/sql-queries-using-zend-db-select/), we are stopping now at subqueries. As you note, the below is a complicate query, with *COUNT()*, *LEFT JOIN()*, *GROUP BY* - select from 3 tables, and make a count from 2 different tables: ```sql SELECT a.id, a.title, (SELECT COUNT(c.track_id) FROM track_files AS c WHERE c.track_id = a.id ) AS `count_files`, COUNT(b.track_id) AS count_courses FROM tracks AS a LEFT JOIN track_courses AS b ON (a.id = b.track_id) GROUP BY a.id ``` Initialize the connection to the MySQL database: ```php $db = Zend_Db::factory('Pdo_Mysql', $dbConnect); ``` ```php $db->select() ->from(array('a'=>'tracks'), array('id', 'title', 'count_files' => new Zend_Db_Expr( '('.$db->select() ->from(array('c'=>'track_files'), array(new Zend_Db_Expr('COUNT(c.track_id)'))) ->where('c.track_id = a.id').')' ) ) ) ->joinLeft(array('b'=>'track_courses'), 'a.id = b.track_id', array('count_courses' => 'COUNT(b.track_id)') ) ->group('a.id'); ``` ## Resources - [Zend_Db series](https://www.dotkernel.com/best-practice/sql-queries-using-zend-db-select/) --- title: "Using LIKE wildcards with Zend_Db" description: "How to use the SQL LIKE condition and its _ and % wildcards, including NOT LIKE, with Zend_Db's quoteInto and quoteIdentifier methods." author: "Teo" date_published: "2010-09-10" canonical_url: "https://www.dotkernel.com/best-practice/using-like-wildcards-with-zend-db/" category: "Best Practice" language: "en" --- # Using LIKE wildcards with Zend_Db ## TL;DR The LIKE condition allows pattern matching in the WHERE clause of SELECT, INSERT, UPDATE, or DELETE statements. The `_` wildcard matches a single character, and `%` matches any string of any length (including zero). This article shows how to use LIKE and NOT LIKE with both wildcards in Zend_Db. Continuing the Zend_Db article [series](https://www.dotkernel.com/best-practice/sql-queries-using-zend-db-select/), let's discuss the LIKE condition. The **LIKE** condition allows you to use wildcards in the *WHERE* clause of an SQL statement. This allows pattern matching. It can be used in any valid SQL statement (*SELECT*, *INSERT*, *UPDATE* or *DELETE*). **LIKE wildcards:** - ***_*** allows you to match a single character - ***%*** allows you to match any string of any length (including zero length) ```php $db = Zend_Db::factory('Pdo_Mysql', $dbConnect); ``` **LIKE _** - Return all ids which start with '1' and second digit is between 0 and 9 (10, 11, 12, ..., 18, 19): ```sql SELECT * FROM `table` WHERE (`id` LIKE '1_' ) ``` ```php $col = $this->db->quoteIdentifier('id'); $where = $this->db->quoteInto("$col LIKE ? ", '1_'); $select = $this->db->select() ->from('table') ->where($where); $result = $this->db->fetchAll($select); ``` - Return all instances whose name is 4 characters long, where the first two characters are 'Fr' and the last character is 'd' (Frad, Fred, Frod, etc.): ```sql SELECT * FROM `table` WHERE (`name` LIKE 'Fr_d' ) ``` ```php $col = $this->db->quoteIdentifier('name'); $where = $this->db->quoteInto("$col LIKE ? ", 'Fr_d'); $select = $this->db->select() ->from('table') ->where($where); $result = $this->db->fetchAll($select); ``` **LIKE %** - Returns all instances that have the 'gallery' string in the *source* field: ```sql SELECT * FROM `table` WHERE (`source` LIKE '%gallery%' ) ``` ```php $col = $this->db->quoteIdentifier('source'); $where = $this->db->quoteInto("$col LIKE ? ", '%gallery%'); $select = $this->db->select() ->from('table') ->where($where); $result = $this->db->fetchAll($select); ``` - Returns all instances that have the 'gallery' or 'folder' strings in the *source* field: ```sql SELECT * FROM `table` WHERE (`source` LIKE '%gallery%' OR `source` LIKE ('%folder%') ) ``` ```php $col = $this->db->quoteIdentifier('source'); $where = $this->db->quoteInto("$col LIKE ? ", '%gallery%'); $where .= $this->db->quoteInto("OR $col LIKE (?) ", '%folder%'); $select = $this->db->select() ->from('table') ->where($where); $result = $this->db->fetchAll($select); ``` **NOT LIKE _** - Returns all 2-digit ids that don't start with *1* (20->99) or have a different number of digits than 2 (1, 2, ..., 8, 9, 100, 101, ...): ```sql SELECT * FROM `table` WHERE (`id` NOT LIKE '1_' ) ``` ```php $col = $this->db->quoteIdentifier('id'); $where = $this->db->quoteInto("$col NOT LIKE ? ", '1_'); $select = $this->db->select() ->from('table') ->where($where); $result = $this->db->fetchAll($select); ``` **NOT LIKE %** - Returns all instances that don't have 'gallery', 'folder' or 'file' strings in the *source* field: ```sql SELECT * FROM `table` WHERE (`source` NOT LIKE ('%gallery%') AND `source` NOT LIKE ('%folder%') AND `source` NOT LIKE ('%file%') ) ``` ```php $col = $this->db->quoteIdentifier('source'); $where = $this->db->quoteInto("$col NOT LIKE (?) ", '%gallery%'); $where .= $this->db->quoteInto("AND $col NOT LIKE (?) ", '%folder%'); $where .= $this->db->quoteInto("AND $col NOT LIKE (?) ", '%file%'); $select = $this->db->select() ->from('table') ->where($where); $result = $this->db->fetchAll($select); ``` **Other example** ```sql SELECT * FROM `table` WHERE `number` LIKE '_6%' ``` ```php $col = $this->db->quoteIdentifier('number'); $where = $this->db->quoteInto("$col LIKE ? ", '_6%'); $select = $this->db->select() ->from('table') ->where($where); $result = $this->db->fetchAll($select); ``` - The *number* column starts with a digit between 4 and 6 (*[4-6]*) - The second character in the *number* column can be anything (*_*) - The third character in the *number* column is 6 (*6*) - The rest of the *number* column can be any string, of any length (*%*) --- title: "What are returning the FETCH functions from Zend_Db" description: "A side-by-side comparison of the legacy query()/next_record()/f() row-fetching style with the fetchAll, fetchAssoc, fetchCol, fetchOne, fetchPairs, and fetchRow methods of Zend_Db_Adapter_Abstract." author: "Teo" date_published: "2010-06-15" canonical_url: "https://www.dotkernel.com/best-practice/what-are-returning-the-fetch-functions-from-zend-db/" category: "Best Practice" language: "en" --- # What are returning the FETCH functions from Zend_Db ## TL;DR Continuing the Zend_Db article series, this article walks through the FETCH methods available on Zend_Db_Adapter_Abstract: fetchAll, fetchAssoc, fetchCol, fetchOne, fetchPairs, and fetchRow. Each method is shown next to the equivalent old-style code built on query(), next_record(), and f(), so the two approaches can be compared side by side. Continuing the Zend_DB article [series](https://www.dotkernel.com/best-practice/sql-queries-using-zend-db-select/), we are stopping now at *FETCH* methods that are in [Zend_Db_Adapter_Abstract](https://docs.laminas.dev/laminas-db/adapter/): ```php array fetchAll (string|Zend_Db_Select $sql, [mixed $bind = array()]) array fetchAssoc (string|Zend_Db_Select $sql, [mixed $bind = array()]) array fetchCol (string|Zend_Db_Select $sql, [mixed $bind = array()]) string fetchOne (string|Zend_Db_Select $sql, [mixed $bind = array()]) array fetchPairs (string|Zend_Db_Select $sql, [mixed $bind = array()]) array fetchRow (string|Zend_Db_Select $sql, [mixed $bind = array()]) ``` To be more easily to follow, in green box is the classical SQL statement, and in blue box is the query written in Zend_Db style. Initialize the connection to the MySQL database: ```php $db = Zend_Db::factory('Pdo_Mysql', $dbConnect); ``` Here is a SQL query that we want to fetch: ```sql $sql = "SELECT id, title FROM files"; $db->query($sql) ``` ```php $select = $db->select() ->from('files', array('id', 'title')) ``` Note: for the old style of fetching we used an old class. What you need to know is: - *query()* method is similar with mysqli_query() from *Mysqli* PHP extension - *next_record()* method is similar with mysqli_next_result() from *Mysqli* PHP extension - *f()* method retrieve the value of the column specified as parameter **fetchAll** ```php while($db->next_record()) { $a[] = array( 'id' => $db->f('id'), 'title' => $db->f('title') ); } ``` ```php $a = $db->fetchAll($select); ``` **fetchAssoc** ```php while($db->next_record()) { $a[$db->f('id')] = array( 'id' => $db->f('id'), 'title' => $db->f('title') ); } ``` ```php $a = $db->fetchAssoc($select); ``` **fetchCol** ```php while($db->next_record()) { $a[] = $db->f('id'); } ``` ```php $a = $db->fetchCol($select); ``` **fetchOne** ```php $db->next_record(); $a = $db->f('id'); ``` ```php $a = $db->fetchOne($select); ``` **fetchPairs** ```php while($db->next_record()) { $a[$db->f('id')] = $db->f('title'); } ``` ```php $a = $db->fetchPairs($select); ``` **fetchRow** ```php $db->next_record(); $a = array( 'id' => $db->f('id'), 'title' => $db->f('title') ); ``` ```php $a = $db->fetchRow($select); ``` --- title: "Why use CURRENT_TIMESTAMP on a field that record date/time?" description: "Why a TIMESTAMP column should default to CURRENT_TIMESTAMP on insert, how ON UPDATE CURRENT_TIMESTAMP keeps it fresh on every update, and how the DEFAULT/ON UPDATE clause combinations behave." author: "Teo" date_published: "2010-06-29" canonical_url: "https://www.dotkernel.com/best-practice/why-use-current-timestamp-on-a-field-that-record-date-time/" category: "Best Practice" language: "en" --- # Why use CURRENT_TIMESTAMP on a field that record date/time? ## TL;DR On a TIMESTAMP field that records date and time when inserting a new record, it's encouraged to use the CURRENT_TIMESTAMP constant as its DEFAULT value. This removes the need to set the value manually from PHP or with MySQL's NOW() function, and the ON UPDATE CURRENT_TIMESTAMP clause can additionally keep the field updated automatically on every row update. Only one TIMESTAMP field per table can be DEFAULT CURRENT_TIMESTAMP. On a *TIMESTAMP field* that records date and time when *inserting* a new record, it is encouraged to use as a *DEFAULT* value, the **CURRENT_TIMESTAMP** constant. **Why?** Because when inserting a new row in the table for the date and time field there is no need to specifically add its value, either by creating it from PHP code with the [Date/ Time functions](https://www.php.net/manual/en/ref.datetime.php) or with MySQL function [NOW()](https://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_now) ```sql ALTER TABLE `user` CHANGE `dateCreated` `dateCreated` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP; ``` CURRENT_TIMESTAMP is also a solution for *updating* date and time fields. Use *`ON UPDATE CURRENT_TIMESTAMP`* clause, if you want the value of the field to be changed automatically each time the row is updated. ```sql ALTER TABLE `user` CHANGE `dateLogin` `dateLogin` TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP; ``` *DEFAULT* and *ON UPDATE* clauses can be used together or separately, depending on your needs: - With both `DEFAULT CURRENT_TIMESTAMP` and `ON UPDATE CURRENT_TIMESTAMP` clauses, the column has the current timestamp for its default value and is automatically updated. - With neither `DEFAULT` nor `ON UPDATE` clauses, it is the same as `DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP`. (Only for the *first* TIMESTAMP field from the table) - With a `DEFAULT CURRENT_TIMESTAMP` clause and no `ON UPDATE` clause, the column has the current timestamp for its default value but is not automatically updated. - With no `DEFAULT` clause and with an `ON UPDATE CURRENT_TIMESTAMP` clause, the column has a default of 0 and is automatically updated. - With a constant `DEFAULT` value, the column has the given default and is not automatically initialized to the current timestamp. If the column also has an `ON UPDATE CURRENT_TIMESTAMP` clause, it is automatically updated; otherwise, it has a constant default and is not automatically updated. For more details check out [MySQL Manual](https://dev.mysql.com/doc/refman/9.7/en/datetime.html) **Note**: Only one timestamp field can be `DEFAULT CURRENT_TIMESTAMP` in a table. --- title: "ZF Is Retired. Laminas MVC Is Retiring. Consider It Solved" description: "What the Laminas MVC retirement announcement means, why legacy MVC platforms are a liability, and how Apidemia helps teams migrate to the Mezzio middleware architecture." author: "Florin Bidirean" date_published: "2025-07-17" canonical_url: "https://www.dotkernel.com/best-practice/zf-is-retired-laminas-mvc-is-retiring-consider-it-solved/" category: "Best Practice" language: "en" --- # ZF Is Retired. Laminas MVC Is Retiring. Consider It Solved ## TL;DR Laminas MVC is retiring, following Zend Framework and Apigility before it, but this doesn't mean everything with a Laminas logo is going away - Mezzio, built on Laminas components, is the fully-functional successor. Maintaining legacy MVC platforms is costly and risky long-term, since the architecture of today and tomorrow is middleware-based, and Apidemia offers a proven, phased migration process to move legacy platforms to Mezzio. It all started with the **announcement**: [Laminas MVC Is Retiring](https://getlaminas.org/blog/2025-06-06-laminas-mvc-is-retiring.html). Some people wrongfully thought everything with a Laminas logo is going away - NOT SO! Read on for a bit of history about Zend and Laminas, what it means to migrate your platform and why it's a decision that should not be taken lightly. ## A Bit of History Laminas MVC is not even the first framework that has reached its end of life - look at Zend Framework and Apigility. Letting go of a flagship product is a **difficult decision**, but it's made easier when you leave a solid alternative in its wake. The **developers** who worked on Laminas MVC already **had something better** and fully-functional in place - **Mezzio microframework**, built using Laminas components. It has itself gone through rigorous development and testing since being released in 2015 when it was known as Zend Expressive, then was renamed into Mezzio to get to its current state. ## What Is the Issue with Legacy Platforms? **Maintaining legacy platforms** over the long term is often a **costly** and **time-consuming** endeavour. Every few years, platform **owners** must consider the viability of **migrating to a newer platform**. Newer platforms implement **modern architectures**, have an **active community** and are actively being **developed and maintained**. They also offer **easier development, expansion and maintenance**, alongside vital **security improvements** and more **reliable dependencies**. Sounds like an easy decision? Sure, but it's a lot of work... And that's when the specialists come into play. We at Apidemia have been using the Zend Framework, Laminas MVC and Mezzio for years. We understand their ins-and-outs intimately, which enables us to **analyze and perform the transfer of a legacy platform to Mezzio effectively**. Working with Mezzio ensures faster execution times, increased security, faster development and long-term reliability from all points of view. We encourage this change and are ready to offer guidance. ## Pain Points The MVC architecture is obsolete. It is yesterday's architecture, fit for monolithic websites. The **architecture of today and tomorrow** is based on middleware, building headless platforms, websites and microservices following the same coding approach. | Pain Point | Apidemia Solution | | --- | --- | | Legacy framework is deprecated and/or has no long-term support | Apidemia helps migrate to modern middleware architecture (Mezzio microframework with Laminas components) | | Legacy applications are hard to maintain | Modern architecture improves code quality, testability and performance | | Migration is risky or expensive | Apidemia uses a proven, phased migration strategy to reduce risk | | Lack of internal development expertise | Apidemia provides end-to-end guidance, refactoring, training and support | ## How Apidemia Handles Migrations Apidemia has created a **complex process** that involves several steps to ensure a **smooth migration**. In a nutshell, the current project functionality must be understood and only then can the move be implemented into the destination platform. Over the long run, the Apidemia team offers support and training. This is the simplified **task list**: - **Code audit & migration strategy** - to understand the code and see what goes where. - **Partial or full migration to Laminas or PSR-compliant frameworks**, like Mezzio or Symfony - this decision impacts both time to implement and cost, negotiated with the client. - **Refactoring and decoupling legacy modules** - the old code must go and be replaced with the new. - **Unit testing and CI/CD pipeline setup** - a vital step to ensure things function the same way in the destination platform. - **Post-migration support and team training** - this step depends on the level of collaboration between the original developers and the Apidemia team, so the more closely they work together, the easier it is to onboard the devs for the long run. ## Resources - [Dotkernel Headless Platform](https://www.dotkernel.com/headless-platform/dotkernel-headless-platform-the-whats-hows-and-whys/) - [Shared Core Submodule in Dotkernel Headless Platform](https://www.dotkernel.com/headless-platform/shared-core-submodule-in-dotkernel-headless-platform/) - [Understanding Middleware](https://www.dotkernel.com/architecture/understanding-middleware/) - [Dotkernel Light](https://www.dotkernel.com/dotkernel/dotkernel-light-starting-with-mezzio-microframework-and-laminas-components/) - [Migrate Laminas MVC to Dotkernel](https://www.apidemia.com/services/migrate-laminas-mvc-to-dotkernel/) --- title: "Naming pattern for PSR-15 handlers in Dotkernel applications" description: "This naming pattern is used in Dotkernel Admin v6 and will also be implemented in the next releases for Frontend and Light." author: "Florin Bidirean" date_published: "2025-04-17" canonical_url: "https://www.dotkernel.com/design-pattern/naming-pattern-for-psr-15-handlers-in-dotkernel-applications/" category: "Design Patterns" language: "en" --- # Naming pattern for PSR-15 handlers in Dotkernel applications > This naming pattern is used in Dotkernel Admin v6 and will also be implemented in the next releases for Frontend and Light. The bigger a project is, the more time it will take to develop and the more people will be assigned to it. Each developer will use slight variations when it comes to naming files, which is not going to be consistent, sometimes not even with work he has done on the same project in the previous month. It might seem ok to use the file names 'CreateUser.php' as much as 'AddUser.php' or 'InsertUser.php', since they perform the same action. But consider that you might have 'CreateUser.php', 'AddProduct.php' and 'InsertOrder.php' in the same application. It's still readable, but chaotic. We will show you a better way to handle file naming, using naming patterns. ## What is a naming pattern? A naming pattern helps you organize and quickly identify your files by using relevant strings in file names like: - What a file refers to. - The action a file performs. - How a file relates to other files. - The author of the file's contents. - The creation date or the event the file refers to. Naming patterns can be defined for different types of files, since `image` files might need other information than `php` files or simple `txt` files used for logs. Here is a list of items to consider: - The file names should be kept as **short** as possible, while retaining relevant items to help outline the file's purpose. - **Abbreviations** are ok to use, but special characters should be avoided, excepting dash and underscore which are fine, no matter the operating system you use. - **Versioning and metadata** can also help visually. - Grouping files into **folders** is also recommended, especially when you are dealing with files that are related. - If **category names** are relevant to use, you can standardize their names by using a shortened version, maybe with 2-3 letters. After defining your naming pattern, the most important item by far is to **communicate the pattern to the team**. A top-level README file with the documentation should be kept handy for any developer who creates new files. ## The naming pattern for Dotkernel Handlers HTTP request handlers are at the core of any web application. They receive a request, process it and return a response. Even the first paragraph above mentions several elements that are relevant. The naming pattern for our `Handlers` contains: - The **method** or verb used by the handler (e.g. GET, POST). - The **resource** name (e.g. Admin, Account). - The performed **action** (e.g. CreateForm, List). - An optional **Form** if the handler returns a form that will perform another action when submitted. - The string **Handler**. In this way, the developer can easily figure out what each handler does, just by looking at the name. We have chosen this wording for the performed actions (or CRUD): - **Create** - **Get** for Read - **Edit** for Update - **Delete** The image below contains the full list of handlers used in Dotkernel Admin. ![Dotkernel Naming Convention](/uploads/article/naming-convention-1024x767.png) ## A practical example Let's assume your application requires you to create products managed by admin users. So how do you go about naming a new set of files for this purpose? First, you need a form to fill out. The form is returned by a `handler` called with `get`. Its purpose is to perform a `create` action for an `product`, hence you name it: `GetProductCreateFormHandler`. Then you send the form data to be saved as a new product. The second `handler` will `create` the new `product` account via `post`, so you get: `PostProductCreateHandler`. You will likely need to update and delete products further down the line, so you create the handlers: `GetProductEditFormHandler`, `PostProductEditHandler` and `PostProductDeleteHandler`. The final handler that makes sense in this group is `GetProductListHandler` that will list all the products you have created, with filtering included. It takes only a minute to build the proper name for each handler, which takes you and other team members no more than a second to figure out what it does. You will thank yourself in the future. ## Resources - [PSR-15](https://www.php-fig.org/psr/psr-15/) - [Dotkernel Application Repositories](https://github.com/dotkernel) --- title: "API Client Migration: From Postman to Bruno" description: "Why the Dotkernel team is considering switching their API testing client from Postman to the offline-focused, Git-native Bruno." author: "Florin Bidirean" date_published: "2026-03-25" canonical_url: "https://www.dotkernel.com/dotkernel-api/api-client-migration-from-postman-to-bruno/" category: "Dotkernel API" language: "en" --- # API Client Migration: From Postman to Bruno ## TL;DR The team has used Postman for years but is considering switching to Bruno, a lightweight, offline-first alternative, reflecting a broader PHP community trend toward local-first, Git-native developer tools. Bruno wins on offline access, version control via Git, performance, and (arguably) security, while Postman still offers a broader feature set for larger, budget-having teams. ## Why We Switched to the Offline-Focused Bruno Every API developer needs a reliable client for testing and interacting with the API - ideally free, able to store and share endpoint collections easily with a team, fast, and secure. Postman has been the team's go-to tool for years, but they are now considering Bruno, part of a general trend in the PHP community toward local-first, Git-native developer tools. ## Comparing Postman to Bruno | Aspect | Postman | Bruno | |---|---|---| | Architecture | Free plan limited to one user account | Fully-offline experience via shared `.bru` files; no restriction on number of developers | | Version control | Handled in the cloud; requires being online (export/import via UI possible) | `.bru` files saved directly in the Git repository, versioned via Git like any other file | | Feature scope | Complete platform for the API lifecycle (mocking, documentation, CI/CD integration) | Focused mainly on interacting with the API, writing simple tests, and building local collections | | Performance | Needs to regularly sync with the cloud and store advanced features in RAM, which can introduce delays | Uses much less RAM and is generally faster | | Security | Offers Single Sign-On (SSO) and Role-Based Access Control (RBAC) | Local files never leave the dev environment, arguably more secure | | Collection sharing | Limited sharing for multi-member dev teams | Can share via Git, `.zip` file, or a single `.yaml` file; Git is the preferred option | ### Comparison Conclusion Postman is currently a better fit for larger teams willing to allocate a budget for a more feature-rich platform. Bruno stores collections in Git, so everything is offline, which the team considers more secure while also being generally faster. ## Alternative API Clients Bruno is only one of several alternatives to Postman: - Hoppscotch - runs in the browser or as a PWA - Insomnia - clear UI and large plugin ecosystem - HTTPie - focuses on terminal-based workflows - Thunder Client - built into Visual Studio Code - Apidog - covers the whole API lifecycle - Yaak - minimal and fast desktop client Any of them can get the job done; the decision comes down to choosing a simple, reliable tool for the foreseeable future. ## Bruno for Dotkernel Bruno currently seems like the best match for the team, offering similar functionality to Postman plus the ability to work completely offline and save endpoint collections to their GitHub accounts. The offline feature weighed most heavily in the decision. ### Tool Migration Since most of the team has only worked with Postman, switching tools can affect efficiency at first, and tool migration can have an emotional impact as developers relearn a new tool's ins and outs. Given Bruno's straightforward approach and reasonable learning curve, the team expects this to be mitigated easily, and views the switch as an expansion of their expertise that avoids getting tied to one tool. ### How Long Will Bruno Last? The team expects Bruno may eventually restrict developers with paid plans too, just like Postman did, but plans to cross that bridge when they get to it. For now, Bruno is becoming their de facto API client, and the whole team is being encouraged to adopt it as soon as possible. ## Resources - [Bruno homepage](https://www.usebruno.com/) - [Hoppscotch](https://hoppscotch.io/) - [Insomnia](https://insomnia.rest/) - [HTTPie](https://httpie.io/) - [Thunder Client](https://www.thunderclient.com/) - [Apidog](https://apidog.com/) - [Yaak](https://yaak.app/) --- title: "API Endpoint to Collect Client Errors" description: "How Dotkernel API's error-report endpoint lets frontend clients submit and log errors that occur on the user's machine." author: "kakapiciu" date_published: "2022-11-07" canonical_url: "https://www.dotkernel.com/dotkernel-api/api-endpoint-to-collect-client-errors/" category: "Dotkernel API" language: "en" --- # API Endpoint to Collect Client Errors When a Frontend (e.g. Angular) sits on top of a Dotkernel API, errors can happen - the API's response may have changed overnight, or a variable may simply be `undefined`. Since the Frontend runs on the user's own client, there's little that can be done about it directly, so an endpoint was created to let clients submit the error message when something goes wrong. ## Usage Send a POST request to your Dotkernel API on the route: ``` https://api.dotkernel.net/error-report ``` With a body: ```shell { "message": "My awesome error!!!" } ``` Note: the error message is stored by default in `/log/error-report-endpoint-log.log`, a separate log for Client, and the message is saved together with a timestamp. ## Resources - [Dotkernel API on GitHub](https://github.com/dotkernel/api) --- title: "Content Negotiation in Dotkernel REST API" description: "How content negotiation works in RESTful APIs, who decides the data format, and how Dotkernel API implements it." author: "Florin Bidirean" date_published: "2024-11-27" canonical_url: "https://www.dotkernel.com/dotkernel-api/content-negotiation-in-dotkernel-rest-api/" category: "Dotkernel API" language: "en" --- # Content Negotiation in Dotkernel REST API ## TL;DR Content negotiation lets clients and servers agree on the format and language of exchanged data. It can be handled server-side or client-side (the latter being more versatile), communicated through HTTP headers or URL patterns, and Dotkernel API implements it out of the box using the `Content-Type` and `Accept` headers. ## What is the Purpose of Content Negotiation? RESTful resources can support multiple representations, and efficient client-server communication depends on both sides agreeing on the exchanged data format - this agreement is content negotiation. It ensures: - **Support for diverse clients**, e.g. `Accept: application/json` or `Accept: application/xml`. - **Data format flexibility**, e.g. using `Accept: application/msgpack` (a binary serialization) instead of JSON for a smaller, easier-to-transfer response. - **Language localization**, e.g. `Accept-Language: en-US`, to respond with content translated into the client's preferred language. ## Who Decides the Data Format? Either the client or the server can decide: - **Server-side negotiation**: the server decides the format based on various factors. This can introduce erroneous assumptions and a more complex server-side implementation, and forces the client to adhere to the server's rules. - **Client-side negotiation**: the client tells the server what format it prefers. This approach is more versatile and makes more sense. There are two ways to communicate the preferred data format: HTTP request headers, or resource URI patterns. ### HTTP Request Headers The `Content-Type` and `Accept` headers determine the data format sent in the request and response. Examples of types include `text/plain`, `text/html`, `application/json`, `application/zip`, `image/gif`, and `image/jpeg`. ```shell Content-Type: application/json, text/plain Accept: application/json ``` If the `Accept` header is not present, the server decides the response format. ### Content Negotiation Using URL Patterns A preferred format can also be communicated via the URL extension: ```shell https://www.example-api.com/record/47.xml https://www.example-api.com/record/47.json ``` or via an extra query parameter: ```shell https://www.example-api.com/record/47?format=xml https://www.example-api.com/record/47?format=json ``` ## Defining Preferences via a Quality Factor The `Accept` header can hold multiple values with an added quality value (`q`, between 0 and 1) that defines preference or priority: ```shell Accept: application/json,application/xml;q=0.9,*/*;q=0.8 ``` In this example, the client accepts both JSON and XML, with JSON preferred. If the server can only satisfy XML, it responds with that; if it can satisfy neither, it responds with whatever it can. ## How Does Dotkernel API Handle Content Negotiation? Out of the box, Dotkernel API uses the `Content-Type` and `Accept` HTTP request headers to handle client-side content negotiation, supporting both `application/json` and `application/hal+json`. These can be changed as development progresses, and per-route content negotiation is also supported. Configuration lives in its own configuration file, validation is automatic, and several explicit errors are handled based on the supported format. ## Resources - [Content Negotiation in Dotkernel API](https://docs.dotkernel.org/api-documentation/v5/core-features/content-validation/) - [Content types on iana.org](https://www.iana.org/assignments/media-types/media-types.xhtml) --- title: "Dotkernel API 1.0.0 Released" description: "Announcement of the Dotkernel API 1.0.0 release, a Zend Expressive 3 application for quickly building APIs, including the libraries it uses and the features it offers out of the box." author: "Alex Karajos" date_published: "2019-12-15" canonical_url: "https://www.dotkernel.com/dotkernel-api/dotkernel-api-1-0-0-released/" category: "Dotkernel API" language: "en" --- # Dotkernel API 1.0.0 Released > Note: Dotkernel API has come a long way since this post was created; a newer version is documented separately. Dotkernel API 1.0.0 was just released. ## What is Dotkernel API? It is a Zend Expressive 3 application aiming to help developers quickly and efficiently develop an API. ## How Does It Work? Under the hood, it uses the following libraries: - `ezimuel/zend-expressive-api` - skeleton application on which this API is based - `dotkernel/dot-annotated-services` (^1.1) - for handling dependency injection in your services - `dotkernel/dot-console` (^0.1.1) - for developing console applications - `dotkernel/dot-errorhandler` (^1.0) - which provides customizable error logging - `dotkernel/dot-mail` (^1.0) - for sending emails via SMTP - `zendframework/zend-expressive-authentication-oauth2` (^1.0) - for OAuth2 authentication - `zendframework/zend-expressive-authorization-rbac` (^1.0) - for role-based permissions - `zendframework/zend-expressive-twigrenderer` (^2.4) - for composing email bodies - `dasprid/container-interop-doctrine` (^1.1) - database abstraction layer - `tuupola/cors-middleware` (^0.9.4) - for automatically sending CORS headers with each request - `swagger-api/swagger-ui` (^3.22) - for creating OpenAPI 3 documentation ## What Does It Offer? Out-of-the-box, Dotkernel API provides the following features: - Secure authentication via OAuth2 - Two user roles: admin and member - Admin users are allowed to manage any user account - Members are allowed to manage only their own accounts - OpenAPI 3 documentation - also an interactive interface that developers can use to integrate your API ## Resources - [Dotkernel API 1.0.0 release on GitHub](https://github.com/dotkernel/api/releases/tag/v1.0.0) - [ezimuel/zend-expressive-api](https://github.com/ezimuel/zend-expressive-api) - [dotkernel/dot-annotated-services](https://github.com/dotkernel/dot-annotated-services) - [dotkernel/dot-console](https://github.com/dotkernel/dot-console) - [dotkernel/dot-errorhandler](https://github.com/dotkernel/dot-errorhandler) - [dotkernel/dot-mail](https://github.com/dotkernel/dot-mail) - [zendframework/zend-expressive-authentication-oauth2](https://github.com/zendframework/zend-expressive-authentication-oauth2) - [zendframework/zend-expressive-authorization-rbac](https://github.com/zendframework/zend-expressive-authorization-rbac) - [zendframework/zend-expressive-twigrenderer](https://github.com/zendframework/zend-expressive-twigrenderer) - [dasprid/container-interop-doctrine](https://github.com/DASPRiD/container-interop-doctrine) - [tuupola/cors-middleware](https://github.com/tuupola/cors-middleware) - [swagger-api/swagger-ui](https://github.com/swagger-api/swagger-ui) - [Newest version of Dotkernel API](https://www.dotkernel.com/headless-platform/version-7-adds-postgresql-native-uuid-and-php-8-5/) --- title: "Dotkernel API Client Side Authorization" description: "How a client application authorizes against a backend built with Dotkernel API, from the authorization request to using the access token." author: "admin" date_published: "2019-08-05" canonical_url: "https://www.dotkernel.com/dotkernel-api/dotkernel-api-client-side-authorization/" category: "Dotkernel API" language: "en" --- # Dotkernel API Client Side Authorization This article covers the basic authorization of a Client application which uses a backend built using Dotkernel API. ## Authorization Request Client application users send a POST request to the backend containing the following JSON object: ```shell { "grant_type": "password", "client_id": "{API_CLIENT}", "client_secret": "{API_CLIENT_SECRET}", "scope": "{SCOPE}", "username": "{USERNAME/EMAIL}", "password": "{PASSWORD}" } ``` ## Authorization Response If the credentials are correct, the API will return a JSON object containing the authentication data: ```shell { "token_type": "Bearer", "expires_in": 86400, "access_token": "...", "refresh_token": "..." } ``` When sending API requests to an endpoint which requires authorization, an `Authorization` header must be present containing `"Bearer {access_token}"`, where `{access_token}` represents the content of the key with the same name found in the authorization response. ## Resources - [Dotkernel API on GitHub](https://github.com/dotkernel/api) --- title: "Dotkernel API Server Side Authorization" description: "How to configure server-side authorization in Dotkernel API, covering no-auth, authentication and authorization access levels, role inheritance, and route permissions." author: "Alex Karajos" date_published: "2019-09-05" canonical_url: "https://www.dotkernel.com/dotkernel-api/dotkernel-api-server-side-authorization/" category: "Dotkernel API" language: "en" --- # Dotkernel API Server Side Authorization ## TL;DR Dotkernel API endpoints can be protected at three levels: no-auth, authentication, and authorization. Access is configured in `config/autoload/authorization.local.php` under the `zend-expressive-authorization-rbac` key, using a `roles` section for role inheritance and a `permissions` section for route access. Authentication endpoints require a valid Bearer token and return `401 Unauthorized` if it's missing, while authorization endpoints additionally check role permissions and return `403 Forbidden`. This article covers the basic authorization of a Server Side application built using [Dotkernel API](https://github.com/dotkernel/api). ## Protecting an Endpoint - no-auth: the resource can be accessed without the need of authentication/authorization - authentication: the resource can be accessed only by authenticated users - authorization: the resource can be accessed only by authenticated AND authorized users Configuring access to the endpoints is done by editing the following config file: `config/autoload/authorization.local.php`. > Note: If this file is missing from your application, locate its dist file `config/autoload/authorization.local.php.dist` and copy it as the above-mentioned `config/autoload/authorization.local.php`. You should look for the array inside this config key: `zend-expressive-authorization-rbac`. ```php 'zend-expressive-authorization-rbac' => , 'member' => , 'guest' => , ], 'permissions' => , ], ] ``` Under the key roles you can define role inheritance. In the above example: - admin inherits from no other role: `'admin' => []` - member inherits from admin: `'member' =>` - guest inherits from member: `'guest' =>` Of course, this setup is just a model, you should not use it in live projects because guests will end up having the same rights as admins. Under the key permissions you can define which routes are accessible to a role. In the above example, a member has access to the routes named avatar, users and user. ### 1. No-Auth Endpoints These endpoints can be accessed without authentication/authorization. Examples could be: login, register, contact etc. Creating a route for such an endpoint will use only the handler(s) responsible for returning the content: ```php $app->get('/users', UserHandler::class, 'users'); ``` ### 2. Endpoints Requiring Authentication These endpoints can be accessed only if a valid `Bearer token` is present in the request headers. Else, the API will return a `401 Unauthorized` response. Creating a route for such an endpoint will have a structure similar to the following example: ```php $app->get('/users', , 'users'); ``` ### 3. Endpoints Requiring Authorization These endpoints can be accessed only if a valid `Bearer token` is present in the request headers. Else, the API will return a `403 Forbidden` response. Creating a route for such an endpoint will have a structure similar to the following example: ```php $app->get('/users', , 'users'); ``` --- title: "Dotkernel API versus Laminas API Tools" description: "A feature-by-feature comparison of Laminas API Tools and Dotkernel API, showing why Dotkernel API is a solid alternative now that Laminas API Tools is archived." author: "Florin Bidirean" date_published: "2024-06-03" canonical_url: "https://www.dotkernel.com/dotkernel-api/dotkernel-api-versus-laminas-api-tools/" category: "Dotkernel API" language: "en" --- # Dotkernel API versus Laminas API Tools ## TL;DR This article compares the basic features of Laminas API Tools and Dotkernel API side by side, covering architecture, versioning, documentation, authentication, and more. It highlights that Dotkernel API is a solid alternative now that Laminas API Tools has been archived, since Dotkernel API uses a modern middleware architecture, MIT license, and evolution-based deprecations instead of traditional versioning. Below we have created an analysis of the basic features available in **Laminas API Tools** and **Dotkernel API**. It's intended to highlight the differences between the two and also to showcase why Dotkernel API is a good alternative for Laminas API Tools, especially considering the latter's archived status. > The table below refers to [Dotkernel API V7](https://github.com/dotkernel/api/tree/7.0). | | **API Tools (formerly Apigility)** | **Dotkernel API** | | --- | --- | --- | | URL | [api-tools](https://api-tools.getlaminas.org/) | [Dotkernel API](https://www.dotkernel.com/api/) | | First Release | 2012 | 2018 | | PHP Version | <= 8.2 | ![PHP Version](https://img.shields.io/packagist/php-v/dotkernel/api) | | Architecture | MVC, Event Driven | Middleware | | OSS Lifecycle | Archived | ![OSS Lifecycle](https://img.shields.io/osslifecycle/dotkernel/api?style=flat&label=) | | Style | REST, RPC | REST | | Versioning | Yes | Deprecations (API Evolution) * | | Documentation | Swagger (Automated) | Postman (*Manual*), OpenAPI 3.0 (Swagger) | | Content-Negotiation | Custom | Custom | | License | BSD-3 | MIT | | Default DB Layer | laminas-db | doctrine-orm 3.x | | Authorization | ACL | RBAC-guard | | Authentication | HTTP Basic/Digest OAuth2.0 | OAuth2.0 | | CI/CD | Yes | Yes | | Unit Tests | Yes | Yes | | Code (Endpoint) Generator | Yes | [dot-maker](https://docs.dotkernel.org/dot-maker/v1/overview/) | | PSR | PSR-7 | PSR-7, PSR-15 | ## Note - Versioning is replaced by [Deprecations](https://docs.dotkernel.org/api-documentation/v6/tutorials/api-evolution/), using an evolution strategy. --- title: "Error reporting endpoint in Dotkernel API" description: "How the Dotkernel API error reporting endpoint lets frontend applications securely report bugs and data errors back to the API, including server-side and frontend setup." author: "Florin Bidirean" date_published: "2024-08-29" canonical_url: "https://www.dotkernel.com/dotkernel-api/error-reporting-endpoint-in-dotkernel-api/" category: "Dotkernel API" language: "en" --- # Error reporting endpoint in Dotkernel API ## TL;DR Dotkernel API includes an error reporting endpoint that lets frontend developers securely report bugs and incorrect data processing back to the API, even when no fatal error shows up in the logs. It works by sending a POST request to `/error-report` with a token in the header; the API validates the request against configured tokens, domains, and IPs before logging the message. Setup involves generating a token, adding it to `config/autoload/error-handling.global.php`, and having the frontend send the `Error-Reporting-Token` and `Origin` headers. Dotkernel API has received a lot of love from our developers, with regular updates to the platform for years. We use Dotkernel API in our projects, so any bugs and issues are addressed as soon as they are found. Still, it's not unlikely that some hidden issues remain in fringe use cases that we simply haven't explored. The occurrence of bugs increases when the API is used in a complex frontend project. Fatal errors are easily found in the API logs, but it's another matter altogether to deal with incorrect data processing that doesn't generate errors in the frontend that interfaces with the API. The error reporting endpoint was designed to allow the frontend developers of your API to report any bugs they encounter in a secure way that is fully under your control. ## Example Case Usage - Frontend developed in Angular. - Frontend developer will use try-catch in the code in order to send frontend errors back to the API. ## How to Use It on the API Side Error reporting is done by sending a POST request to the `/error-report` endpoint, together with a token in the header. In the sections below we will detail how to configure error reporting in your API and how the endpoint is used by the frontend developers. ### Generating a Token and Adding It to Your API Config First you need to generate a token for your request. This is done by using the below command. ```bash php ./bin/cli.php token:generate error-reporting ``` The resulting token has this format `0123456789abcdef0123456789abcdef01234567`. Note: this example is provided just to let you know what to look for. Copy the generated token in your `config/autoload/error-handling.global.php` file. It should look similar to the example below. Your API can have multiple tokens, if needed. ```php return , ... ] ] ``` ### Validation Mechanism Behind the scenes, the API validates your configuration and lets you know if any config items prevent the submission of the error report. Below are the requirements for an application to be able to send error messages to Dotkernel API. - Server-side requirements stored in `config/autoload/error-handling.global.php` (these can be set/overwritten in `config/autoload/local.php`): - All keys (`enabled`, `path`, `tokens`, `domain_whitelist` and `ip_whitelist`) must exist under `ErrorReportServiceInterface::class`. - The error reporting feature must be enabled by setting `ErrorReportServiceInterface::class` . `enabled` to `true`. - `ErrorReportServiceInterface::class` . `path` must have a value; if the destination file does not exist, it will be created automatically. - `ErrorReportServiceInterface::class` . `tokens` must contain at least one token. - At least one of `ErrorReportServiceInterface::class` . `domain_whitelist`/`ip_whitelist` must have at least one value. Note: In `src/App/src/Service/ErrorReportService.php`, the method `checkRequest()` tries to validate the request by checking matches for `domain_whitelist` with `isMatchingDomain()` and for `ip_whitelist` with `isMatchingIpAddress()`. If both return `false`, a `ForbiddenException` is thrown and the error message does not get stored. - Application-side requirements: - Send the `Error-Reporting-Token` header with a valid token previously stored in `config/autoload/error-handling.global.php` in the `ErrorReportServiceInterface::class` . `tokens` array. - Send the `Origin` header set to the application's URL; this is the application that sends the error message. Note: - The tokens under `ErrorReportServiceInterface::class` . `tokens` do not expire. - The log file stores the token value too, making it easy to identify which application sent the error message. If your request passes all the checks, the message is saved in the log file specified in `ErrorReportServiceInterface::class` . `path`. ### Tips and Tricks If there are multiple applications that report errors to your API, you can assign a different error reporting token for each. The tokens support key-value pairs where: - The key is an alias relevant to the assigned application that uses it. - The value is the token itself. Example: ```php // ... return , ], ]; ``` The log file will have entries similar to the below: > Demo error message The inclusion of the token helps you identify the source of the error message. In our example, it's the application that uses the `0123456789abcdef0123456789abcdef01234567` token, which is assigned to the application `frontend`. ## How to Use It on the Frontend Side (Angular Example) The API developer sends a generated token to the frontend developer who will save it in their `environment.staging.ts` and/or `environment.prod.ts`. From then on, it's the frontend developer's job to set up an error reporting function similar to the one below. ```typescript postError(body: object): Promise { return new Promise((resolve, reject) => { return this.http.post(API_ENDPOINT + 'error-report', body , {headers: new HttpHeaders({'Error-Reporting-Token': 'TOKEN', 'Origin': 'https://example.com'})})).subscribe({ next: (response: any) => { resolve(response); }, error: (e: HttpErrorResponse) => reject(e), complete: () => console.info('Error on sending error'), }); }); } ``` Whenever an error is found, the frontend will call `postError()` with a relevant description under `message`. ```typescript apiService.postError({message: 'ERROR MESSAGE'}) ``` ## Conclusion The error reporting feature in Dotkernel API is a secured and highly configurable tool for users of your API to report any unwanted behavior. More often than not, a detailed error report will help developers understand how to replicate the issue and fix it in due course. This article is also included in the full API documentation [https://docs.dotkernel.org/api-documentation/v5/core-features/error-reporting](https://docs.dotkernel.org/api-documentation/v5/core-features/error-reporting). --- title: "How to implement MailChimp in Dotkernel API" description: "A step-by-step guide to integrating MailChimp into a Dotkernel API instance using the drewm/mailchimp-api library, from installation to wiring up a factory in the ConfigProvider." author: "Alex Karajos" date_published: "2020-01-04" canonical_url: "https://www.dotkernel.com/dotkernel-api/how-to-implement-mailchimp-in-dotkernel-api/" category: "Dotkernel API" language: "en" --- # How to implement MailChimp in Dotkernel API ## TL;DR This is a step-by-step guide to adding MailChimp support to a Dotkernel API instance using the `drewm/mailchimp-api` library. It covers installing the library, creating a MailChimp config file, building a factory that returns a `DrewM\MailChimp\MailChimp` instance, and registering that factory in `ConfigProvider.php` so it can be injected wherever needed. This article will walk you through the process of implementing MailChimp into your instance of [Dotkernel API](https://github.com/dotkernel/api) using [drewm/mailchimp-api](https://github.com/drewm/mailchimp-api). Step 1: Add the library to your application using the following command: ```bash composer require drewm/mailchimp-api ``` Step 2: Create configuration file `config/autoload/mailchimp.global.php` and paste the following content inside of it: ```php get('config')['mailChimp'] ?? []; return new MailChimp($config['apiKey'] ?? ''); } } ``` Step 4: Let your application use this factory by adding it to the main ConfigProvider. To do this, open file `src/App/src/ConfigProvider.php` and locate the method called `getDependencies()`. Inside this method, locate the key `factories` which points to an array. Inside this array add the following line: ```php MailChimp::class => MailChimpFactory::class, ``` Make sure you add the corresponding uses: ```php use Api\App\MailChimp\Factory\MailChimpFactory; use DrewM\MailChimp\MailChimp; ``` After this, you can start using the library by @Injecting `MailChimp::class` where it's needed. --- title: "OpenAPI implementation in Dotkernel API" description: "An overview of the OpenAPI Specification, why it complements tools like Postman, and how Dotkernel API implements OpenAPI documentation across its modules." author: "Florin Bidirean" date_published: "2024-07-30" canonical_url: "https://www.dotkernel.com/dotkernel-api/openapi-implementation-in-dotkernel-api/" category: "Dotkernel API" language: "en" --- # OpenAPI implementation in Dotkernel API ## TL;DR OpenAPI is a specification for describing an API's structure in a language-agnostic, machine-readable way, offering benefits like standardization, automatic documentation, upfront design, and better collaboration compared to a tool like Postman. Dotkernel API has full OpenAPI support: each module (Admin, App, User) documents its endpoints in an `OpenAPI.php` file, which `zircote/swagger-php` turns into documentation rendered via Swagger UI or Redoc. Testing protected endpoints in Swagger UI requires generating an authentication token that matches the endpoint's required privileges. ## What Is OpenAPI? The OpenAPI Specification provides a consistent way to develop and interact with an API. It defines API structure and syntax in a universal way, regardless of the programming language used in the API's development. API specifications typically use YAML or JSON to share and use the specification. They allow users of the API to quickly discover how it works by describing its elements, e.g. endpoints, request and response formats, security mechanisms and more. While not mutually exclusive, OpenAPI has several benefits over Postman: - API standardization: this offers a standard way to describe and document endpoints, request/response models, and other details of your API that enforces design best practices. Postman has no focus on this topic. - Automatic generation of API documentation: create comprehensive, machine-readable documentation that helps developers understand how to interact with your API. Postman is not designed to explain the API's components. - API design and development: define your API specification, most commonly using YAML and JSON formats, before starting development. Postman is used only to test an existing, completed endpoint. - Improved collaboration: this benefits frontend and backend developers, as well as operations teams. Postman's free tier is aimed more towards individual or small team development. - API gateways and management: a wide range of tools and platforms that support OpenAPI allow more streamlined monitoring and management of APIs. Postman has environment management, but primarily on the developer's machine. Other benefits from using OpenAPI: - Code generation: automatically generate client code, server stubs, API documentation and even test cases to ensure consistency between the API documentation and implementation. - Interoperability: standardization using OpenAPI ensures that the API can interface with other systems. - Testing and validation: the specification can generate tests to catch bugs early on and ensure correct functionality. - Versioning and change management: keeps track of changes and ensures backward compatibility. ## The Importance of API Documentation API documentation, in general, is crucial for several reasons. It serves multiple stakeholders that use the API for development, integration and maintenance. - Faster developer onboarding, adoption and integration: helps developers understand the API better and reduces the learning curve for adopting and integrating the API into other systems. The API documentation should be publicly available, especially if the API is public. It's even more beneficial if the documentation is integrated with a developer portal. - Better collaboration: promotes consistency and reduces misunderstandings between developers and users. - Better API quality and maintenance: includes details on how to properly use the API, from its data types and required parameters, to error handling procedures. This helps maintain existing functionality when changes are implemented. - Helps troubleshooting: it defines the correct functionality that helps developers and maintainers find and fix bugs more effectively. ## OpenAPI in Dotkernel API Dotkernel API has full support for OpenAPI, from describing the endpoints and generating the documentation, to rendering and testing the endpoints. Each module (Admin, App, User) in Dotkernel API contains a file named `OpenAPI.php`. In this file you must document all of the endpoints from `RoutesDelegator.php`. The entries in `OpenAPI.php` have several descriptive items, the most important being method, request and response. These are used to generate a documentation file from the command line. The static documentation file is rendered using Swagger UI or Redoc in a user-friendly way. You can read more about this [starting here](https://docs.dotkernel.org/api-documentation/v5/openapi/introduction/) and its subsequent pages. ### Describing OpenAPI Components All OpenAPI components require a handful of components that are universally valid for a given project. These are below: - OA\Info contains basic information on your project, like version and name. - OA\Server has one or more urls to a target host. - OA\SecurityScheme describes the protection for the endpoint. - OA\ExternalDocumentation has a url and description for extended documentation related to an item. - OA\Schema describes a object (e.g. entity) or collection of objects in your project. Read more details about the above [here](https://docs.dotkernel.org/api-documentation/v5/openapi/initialized-components/). Once you have your basic components defined, you can begin work on the endpoints. The endpoints already made available in Dotkernel API are documented, so you must do the same for the new endpoints you create in your project. This is done by defining these items: - the request object (Get, Post, Patch, Put, Delete) - the path to the resource - the endpoint's summary and description - the query/path parameters, if required - the request body, if required - the security scheme, if required - the response Wherever it's appropriate, schemas should be used to ensure consistency. The optional 'tags' item can be used to group operations together. Read more [here](https://docs.dotkernel.org/api-documentation/v5/openapi/initialized-components/). ### Generating the Documentation The documentation is generated using [zircote/swagger-php](https://github.com/zircote/swagger-php). It uses the descriptions you added in the `OpenAPI.php` files to build the documentation file. The documentation contents can be listed in the command line or saved to a file in yaml of json format. You can read more [here](https://docs.dotkernel.org/api-documentation/v5/openapi/generate-documentation/). ### Alternatives for Rendering the Documentation Once you have the documentation generated, it can be rendered in two ways: - Swagger UI allows you to visualize and interact with the API's resources without worrying about the implementation logic. - Redoc lists the documentation in read-only mode, detailing example requests and responses. ### Handling Authentication for Swagger UI Most endpoints for your API should be protected, so to access them you are required to generate an authentication token (AuthToken). The token is related to the user type, so make sure to check the privileges required for the endpoint you are testing. After you submit the token, you can test the endpoints as an authenticated user. Clicking on the 'Try it out' button will activate the required parameter input fields and the textarea for the request body. The 'Execute' button will send the request and return the response, along with its HTTP status code. You can read more details [here](https://docs.dotkernel.org/api-documentation/v5/openapi/use-documentation/). --- title: "What \"Production Ready\" Means for Dotkernel API" description: "What Dotkernel API's production-ready claim actually covers, what still sits on you (rate limiting, gateway, federated identity, error tracking, health checks, caching), and where to read the full checklist before going live." author: "arhimede" date_published: "2026-09-09" canonical_url: "https://www.dotkernel.com/dotkernel-api/what-production-ready-means-for-dotkernel-api/" category: "Dotkernel API" language: "en" --- # What "Production Ready" Means for Dotkernel API ## TL;DR Dotkernel API ships a complete, tested application layer — pipeline, OAuth2 auth, RBAC, validation, error responses, OpenAPI. It does not ship the infrastructure layer around it: rate limiting, an API gateway, federated identity, error tracking, health checks, or caching/background jobs. Those are deliberate boundaries, not gaps, and the linked documentation page lists each one with what to configure before going live. Dotkernel API describes itself as production ready, and it is — but the phrase covers less ground than most people assume, and the difference is worth naming. ## What Ships in the Box A REST API needs a lot of machinery before it can serve a single useful request. Dotkernel API brings all of it already assembled: a readable middleware pipeline, OAuth2 authentication, role-based access control, request validation, standardised error responses and a generated OpenAPI specification. None of that is scaffolding you finish yourself. It is written, tested and documented, and it is the reason you can go from an empty project to a working endpoint in an afternoon. That is what production ready means here. The application is complete. ## What You Still Own What it does not mean is that everything a public API needs on the day it goes live is included. Around the application sits a second layer, and that layer is yours: - **Traffic control.** Nothing limits how fast a client can call your endpoints. Your login endpoint will answer a brute-force attempt as patiently as it answers a real user. - **An API gateway.** Certificates, per-customer quotas, API keys, edge caching and a web application firewall all live in front of the application, not inside it. - **Federated identity.** Dotkernel API issues its own tokens. If your organisation signs in through Keycloak, Auth0, Microsoft Entra ID or Okta, connecting the two is work you do. - **Somewhere for errors to go.** Errors are written to a file on the server. They are not sent to Sentry or any other tracking service, which means that by default, nobody is told when something breaks. - **Health checks and monitoring.** There is no endpoint a load balancer can ask "are you actually working?", and no metrics coming out of the application at all. - **Caching and background work.** Responses are not cached, and email is sent while the user waits. None of these are bugs. Most of them are decisions. ## Why the Line Is Drawn There Rate limiting is the clearest example. It genuinely belongs in your infrastructure, where it can protect every node at once, rather than inside application code that only sees its own traffic. The same argument applies to certificates, secrets and log shipping. A framework that shipped opinionated versions of all of these would be a framework you spend your first week fighting. The real problem was never the missing pieces. It was that nobody wrote down which pieces were missing. A team can reasonably read "production ready", deploy on Friday, and only discover on Monday that the login endpoint has no rate limit — not because they were careless, but because nothing told them that half was theirs. ## Where the Line Is Moving Some of it is moving inward. There are open proposals to add a health check endpoint, to investigate a rate limiting middleware for demonstration purposes, and to extend caching. The boundary is not fixed, and it is being discussed in the open. ## Start Here We have added a page to the documentation that names every gap, says whether it belongs in your application or in the platform in front of it, and gives you the concrete thing to configure for each one. It closes with a short ordered checklist of what to do before you go live. Read it before your first deployment, not after: **[Production Readiness — Dotkernel API documentation](https://docs.dotkernel.org/api-documentation/v7/reference/production-readiness/)** ## Resources - [Production Readiness](https://docs.dotkernel.org/api-documentation/v7/reference/production-readiness/) — the full documentation page - [Basic Security](https://docs.dotkernel.org/api-documentation/v7/security/basic-security/) — application-level hardening before launch - [Dotkernel API on GitHub](https://github.com/dotkernel/api) — issues and open proposals --- title: "Adding a CORS implementation to Zend Expressive" description: "A guide on how to add a CORS implementation to an existing Dotkernel3 project using Tuupola's Cors Middleware package." author: "Gabi DJ" date_published: "2019-04-08" canonical_url: "https://www.dotkernel.com/dotkernel/adding-a-cors-implementation-to-zend-expressive/" category: "Dotkernel" language: "en" --- # Adding a CORS implementation to Zend Expressive ## TL;DR When a client-side request is blocked with a "No 'Access-Control-Allow-Origin' header" error, it's because the server isn't sending the header that allows a browser to access its data (most common when fetching JSON to process with JavaScript). This guide adds CORS support to a Zend Expressive / Dotkernel3 project using Tuupola's Cors Middleware package. ## The issue If you're facing the error: > "Access to XMLHttpRequest at 'url' has been blocked by cors policy. > No 'Access-Control-Allow-Origin header is present on the requested resource." it means the server didn't send the header that lets you access its data through a local client (e.g. a browser). This issue is most common when trying to get data (usually JSON) that you want to process using JavaScript. The error looks similar to the image below: ![](/uploads/article/Screenshot-2019-04-06-at-15.03.21-1024x165-1-1024x165.png) ## The solution A simple implementation uses [Tuupola's Cors Middleware](https://packagist.org/packages/tuupola/cors-middleware) package. (This article was inspired by [akrabat.com/implementing-tuupola-cors-in-expressive](https://akrabat.com/implementing-tuupola-cors-in-expressive/).) ### 1. Add the package to your project ```shell composer require tuupola/cors-middleware ``` At the time of writing, the current package version is 0.9.4. ### 2. Create the CORS config file Create a `cors.global.php` file in the `config/autoload` directory: ```php return [ 'cors' => [ "origin" => [], "methods" => [], "headers.allow" => [], "headers.expose" => [], "credentials" => false, "cache" => 0, ], 'dependencies' => [], ]; ``` ### 3. Create a factory for the middleware The factory extracts the config from the `cors` key (or initializes an empty array) and instantiates the Tuupola CORS middleware: ```php get('config')['cors'] ?? []; return new CorsMiddleware($corsConfig); } } ``` ### 4. Register the CORS middleware Back in `cors.global.php`, register the middleware so the factory above is used to create it: ```php [ "origin" => [], "methods" => [], "headers.allow" => [], "headers.expose" => [], "credentials" => false, "cache" => 0, ], 'dependencies' => [ 'factories' => [ CorsMiddleware::class => CorsMiddlewareFactory::class, ] ] ]; ``` ### 5. Add the CorsMiddleware to the pipeline In `config/pipelines.php`: ```php // don't forget the use statement use Tuupola\Middleware\CorsMiddleware; return function (Application $app, MiddlewareFactory $factory, ContainerInterface $container) : void { // ... $app->pipe(CorsMiddleware::class); // ... }; ``` Add the CORS middleware **after** the Error handler and **before** the middleware providing the data you want to access, to make sure everything runs smoothly. This should get your project working with CORS. ## Resources - [Tuupola's Cors Middleware package](https://packagist.org/packages/tuupola/cors-middleware) - [Implementing Tuupola CORS in Expressive (inspiration article)](https://akrabat.com/implementing-tuupola-cors-in-expressive/) --- title: "Adding Composer support in your Dotkernel project" description: "The steps needed to add Composer support to a Dotkernel 1.x project, or 'composify' it." author: "Gabi DJ" date_published: "2016-04-04" canonical_url: "https://www.dotkernel.com/dotkernel/adding-composer-support-in-your-dotkernel-project/" category: "Dotkernel" language: "en" --- # Adding Composer support in your Dotkernel project ## TL;DR Composer is an application-level package manager that auto-loads dependencies (and custom classes) on demand. This article covers the steps needed to add a composer.json file to a Dotkernel project, run `composer update`, and safely require the generated autoloader so the project works whether or not Composer is present. ## First things first The Dotkernel project must have a **composer.json** file so that Composer can work. It should look like this: ```json { "require" : { "zendframework/zendframework1" : "1.12.*", "mobiledetect/mobiledetectlib" : "2.8.*" }, "require-dev" : { "php" : ">=5.4.0" } } ``` Note: `zendframework/zendframework1` may not be necessary if you already have ZendServer running or the Zend Framework folder within `/usr/share/`. This file makes sure: - Zend Framework is present and at version > 1.12.* - MobileDetect is present and at version > 2.8 - The PHP executable is at least at version > 5.4.0 (only for development, because it is not present in the main `require`) The dependencies provided in the `require` section are also loaded for development purposes if not provided in `require-dev`. In order to have these components installed, run the following command in your Dotkernel root path: ```shell composer update ``` If the `vendor` folder is present, Composer will check for updates and update the packages as needed. If the `vendor` folder does not exist, Composer will create it, containing all the requested packages, along with an autoload file used to load the dependencies/packages. ## Adding Composer Support to Dotkernel The autoload file created by Composer is used to load the packages: ```php $composerAutoLoaderPath = realpath(APPLICATION_PATH.'/vendor/autoload.php'); require_once($composerAutoLoaderPath); ``` But what if the file does not exist, or Composer is not present? First make sure the Composer autoload path exists, and only load the dependencies if the autoload file was found: ```php $composerAutoLoaderPath = realpath('./vendor/autoload.php'); $composerEnabled = file_exists($composerAutoLoaderPath); if ($composerEnabled == true) { require_once($composerAutoLoaderPath); } else { // handle the error gracefully // or load fallbacks - if exist } ``` The variable `$composerEnabled` will be true only if the Composer path exists, so the application behavior can be controlled if Composer is not present. Later on, the packages can be used like this: ```php use VendorName\PackageName\ClassName as MyDependency; $myDependency = new MyDependency($neededArguments); $myDependency->doSomething(); ``` This article works for any **Dotkernel 1.x** version if your server is running **PHP >5.4.0**. ## Resources - [Composer install / PHP dependency manager tutorial](https://www.codementor.io/php/tutorial/composer-install-php-dependency-manager) --- title: "Autologin using Cookie / Remember Me in Dotkernel" description: "A step-by-step guide to implementing a Remember Me / autologin feature in Dotkernel Frontend." author: "SergiuB" date_published: "2022-07-18" canonical_url: "https://www.dotkernel.com/dotkernel/autologin-cookie-remember-me-feature/" category: "Dotkernel" language: "en" --- # Autologin using Cookie / Remember Me in Dotkernel ## TL;DR This feature automatically logs in a user who checks the "remember me" box at login. It has been implemented in [Dotkernel Frontend](https://github.com/dotkernel/frontend) starting from Release 3.3.0, and requires changes across the login form, a new entity/migration, a new middleware, config, and the user service/repository/controller. ## Add remember me button to user interface Navigate to `src/User/templates/user/login.html.twig` and, under the password element, add: ```twig
{% set rememberMe = form.get('rememberMe') %} {{ formElement(rememberMe) }}

Remember me

``` Then navigate to `src/User/src/Form/LoginForm.php` and add the following element to your form: ```php $this->add([ 'name' => 'rememberMe', 'type' => 'checkbox', 'attributes' => [ 'class' => 'tooltips', 'data-toggle' => 'tooltip', 'title' => 'Remember me', ], ]); ``` Then navigate to `src/User/src/InputFilter/LoginInputFilter.php` and add a filter for the new element: ```php $this->add([ 'name' => 'rememberMe', 'filters' => [ ['name' => 'StringTrim'] ], 'validators' => [ [ 'name' => 'NotEmpty', 'break_chain_on_failure' => true, ] ] ]); ``` To style the button, navigate to `src/App/assets/scss/components/_profile.scss` and add: ```scss .remember-me-checkbox { input { display: block; float: left; margin: 4px 6px 10px 0; width: auto; height: auto; } } ``` After making the changes, compile the CSS so the button styling takes effect: ```shell npm run prod ``` ## Add functionality to remember me button 1. Navigate to `src/User/src/Entity`, create a new entity named `UserRememberMe.php`, modeled on [UserRememberMe](https://github.com/dotkernel/frontend/blob/3.0/src/User/src/Entity/UserRememberMe.php). 2. Create a migration file for the new table: ```shell vendor/bin/phinx create --configuration=config/migrations.php RememberUserSchema ``` 3. Modify the generated migration file as in [user_remember_schema](https://www.dotkernel.com/dotkernel/autologin-cookie-remember-me-feature/), then run it against the database: ```shell vendor/bin/phinx migrate --configuration=config/migrations.php ``` The table generated by the migration is used to store data from the cookie, which helps log the user in automatically. 4. Create a new middleware at `src/App/src/Middleware/RememberMeMiddleware.php`, modeled on [RememberMeMiddleware](https://github.com/dotkernel/frontend/blob/3.0/src/App/src/Middleware/RememberMeMiddleware.php). 5. Register the middleware in `config/pipeline.php` as shown in [pipeline](https://github.com/dotkernel/frontend/blob/3.0/config/pipeline.php). 6. To generate the cookie, add a new key to `config/autoload/local.php`: ```php 'rememberMe' => [ 'cookie' => [ 'name' => 'rememberMe', 'lifetime' => 3600 * 24 * 30, 'samesite' => 'Lax', 'secure' => false, 'httponly' => true ] ], ``` 7. Edit `src/User/src/Service/UserService.php`: add two new properties, `$defaultSessionManager` (to get config) and `$repository` (to get repository), then add the methods `getRepository()`, `addRememberMeToken()`, `deleteRememberMeCookie()` as in [UserService](https://github.com/dotkernel/frontend/blob/3.0/src/User/src/Service/UserService.php) (and add the new methods to the interface if needed). 8. Edit `src/User/src/Repository/UserRepository.php` and add the methods `saveRememberUser()`, `getRememberUser()`, `findRememberMeUser()`, `deleteExpiredCookies()`, `removeRememberUser()` as in [UserRepository](https://github.com/dotkernel/frontend/blob/3.0/src/User/src/Repository/UserRepository.php). 9. Edit `src/User/src/Controller/UserController.php`: add a new property called `$config`, and edit `loginAction()` and `logoutAction()` as in [UserController](https://github.com/dotkernel/frontend/blob/3.0/src/User/src/Controller/UserController.php). ## Resources - [Dotkernel Frontend on GitHub](https://github.com/dotkernel/frontend) - [UserRememberMe entity example](https://github.com/dotkernel/frontend/blob/3.0/src/User/src/Entity/UserRememberMe.php) - [Remember user schema migration example](https://www.dotkernel.com/dotkernel/autologin-cookie-remember-me-feature/) - [RememberMeMiddleware example](https://github.com/dotkernel/frontend/blob/3.0/src/App/src/Middleware/RememberMeMiddleware.php) - [pipeline.php example](https://github.com/dotkernel/frontend/blob/3.0/config/pipeline.php) - [UserService example](https://github.com/dotkernel/frontend/blob/3.0/src/User/src/Service/UserService.php) - [UserRepository example](https://github.com/dotkernel/frontend/blob/3.0/src/User/src/Repository/UserRepository.php) - [UserController example](https://github.com/dotkernel/frontend/blob/3.0/src/User/src/Controller/UserController.php) --- title: "Avoid routing through bootstrap of non existent files" description: "How to stop missing static files from being routed through the bootstrap and logging out users whose session regenerates on each request." author: "admin" date_published: "2013-11-29" canonical_url: "https://www.dotkernel.com/dotkernel/avoid-routing-through-bootstrap-of-non-existent-files/" category: "Dotkernel" language: "en" --- # Avoid routing through bootstrap of non existent files In some cases you may encounter missing files: images, CSS, or JS files. All those missing files are processed by the current bootstrap: `index.php`. If the session is set to regenerate on each request, as a normal security measure, the currently logged-in user is logged off, because the session ID is different now. To avoid this, below the following line: ``` RewriteEngine On ``` add the line: ``` RewriteCond %{REQUEST_FILENAME} (\.gif|\.jpg|\.png|\.css|\.js)$ ``` Save, and don't forget to test. --- title: "Commitment to PHP - new Zend Certified Engineers - ZCE - in our team" description: "Two more team members passed the ZCE exam, bringing the team's total to 5 Zend Certified Engineers." author: "admin" date_published: "2012-04-20" canonical_url: "https://www.dotkernel.com/dotkernel/commitment-to-php-new-zend-certified-engineers-zce-in-our-team/" category: "Dotkernel" language: "en" --- # Commitment to PHP - new Zend Certified Engineers - ZCE - in our team Another 2 of our team members passed the ZCE exam. Now we are 5. That means we are really taking PHP into serious consideration, and at the very least we have good technical skills. See the [Zend Yellow Pages](https://www.zend.com/store/education/certification/yellow-pages.php#list-cid=0&sid=&certtype_zf=1&certtype_php=1&certtype=&firstname=&lastname=&company=Dotboost%20Technologies&ClientCandidateID=). ## Resources - [Zend Yellow Pages listing](https://www.zend.com/store/education/certification/yellow-pages.php#list-cid=0&sid=&certtype_zf=1&certtype_php=1&certtype=&firstname=&lastname=&company=Dotboost%20Technologies&ClientCandidateID=) --- title: "Dependency Injection made easy in Laminas/Mezzio applications" description: "Introduces Dotkernel's dot-dependency-injection package, which autowires constructor dependencies in Laminas/Mezzio applications via a PHP attribute instead of a hand-written factory per class." author: "Claudiu Pintiuta" date_published: "2024-06-20" canonical_url: "https://www.dotkernel.com/dotkernel/dependency-injection-made-easy-in-laminas-mezzio-applications/" category: "Dotkernel" language: "en" --- # Dependency Injection made easy in Laminas/Mezzio applications ## TL;DR Dotkernel's dot-dependency-injection package autowires constructor dependencies in Laminas/Mezzio (and other PSR-11) applications, removing the need to write and maintain a custom factory class for every service. Instead of a bespoke factory, you add an attribute to the class constructor and register a single shared AttributedServiceFactory in your ConfigProvider. The package requires Doctrine ORM but can still be used in applications that don't integrate Doctrine, and it also supports injecting Doctrine repositories directly instead of fetching them from the EntityManager. > Note: The package requires Doctrine ORM. Still, it can be used in applications which do not integrate Doctrine. So, first thing first, the problem. You have a Laminas / Mezzio application with a bunch of services that you need to use in a, let's say, controller class or in any other class, and you are tired of building, updating, and maintaining factories every time you add a new dependency to your class. Dotkernel has you covered. We built a tool to autowire those dependencies in your class. There is no need for factories for every class you make. Just use one "factory" class that you tie to your custom class in the config, and that's it. Sounds easy, right? Let's finish with the chat and speak some code, first showing the problem and then the solution. > The examples below are from the [Dotkernel API framework](https://github.com/dotkernel/api), but the pattern applies to all laminas and mezzio applications and to all PSR-11 applications. ```php class UserHandler implements RequestHandlerInterface { public function __construct( protected UserServiceInterface $userService, protected array $config, ) { } } ``` Above, we have a UserHandler (Controller), and we have the required dependencies: `UserService` and `config`. Normally, we would build a factory for this to get things from the container and put them in the config provider like this: ```php class UserHandlerFactory { /** * @throws ContainerExceptionInterface * @throws NotFoundExceptionInterface */ public function __invoke(ContainerInterface $container) { $userService = $container->get(UserService::class); assert($userService instanceof UserService); $config = $container->get('config'); return new UserHandler($userService, $config); } } ``` And in the config provider, we would have the following: ```php public function getDependencies(): array { return ]; } ``` In one more example, let's look at the real-world required dependencies for `UserService`, the dependency that is required for `UserHandler`. ```php class UserService implements UserServiceInterface { public function __construct( protected UserRoleServiceInterface $userRoleService, protected MailService $mailService, protected TemplateRendererInterface $templateRenderer, protected OAuthAccessTokenRepository $oAuthAccessTokenRepository, protected OAuthRefreshTokenRepository $oAuthRefreshTokenRepository, protected UserRepository $userRepository, protected UserDetailRepository $userDetailRepository, protected UserResetPasswordRepository $userResetPasswordRepository, protected LoggerInterface $logger, protected array $config = [], ) { } } ``` Now consider that we need to build the factory for this and update it when we add a new dependency, and so on. We'd also need to build the logic in the factory to handle any dependencies missing from the container. Painful, right? Now let's use Dotkernel's [dot-dependency-injection](https://github.com/dotkernel/dot-dependency-injection) package to inject the required dependency into your class. After you install the package, your class needs to `use Dot\DependencyInjection\Attribute\Inject`, then you need to add the `#` attribute to the constructor definition to specify which dependencies should be injected. ```php use Dot\DependencyInjection\Attribute\Inject; class UserHandler implements RequestHandlerInterface { # public function __construct( protected UserServiceInterface $userService, protected array $config, ) { } } ``` Add the `Dot\DependencyInjection\Factory\AttributedServiceFactory` class to your `ConfigProvider`: ```php public function getDependencies(): array { return ]; } ``` That's right, the `AttributedServiceFactory` class is the only one you need to add to your config, so you are ready to go. This class will "build" the factory for you and will handle all the logic if any dependencies are not found in the container, with appropriate exceptions and messages. One more time, let's see how the `UserService` will look now. ```php class UserService implements UserServiceInterface { use Dot\DependencyInjection\Attribute\Inject; # public function __construct( protected UserRoleServiceInterface $userRoleService, protected MailService $mailService, protected TemplateRendererInterface $templateRenderer, protected OAuthAccessTokenRepository $oAuthAccessTokenRepository, protected OAuthRefreshTokenRepository $oAuthRefreshTokenRepository, protected UserRepository $userRepository, protected UserDetailRepository $userDetailRepository, protected UserResetPasswordRepository $userResetPasswordRepository, protected LoggerInterface $logger, protected array $config = [], ) { } } ``` ## And, That's Not All. If you use Doctrine and the repository pattern and you don't want to get your repository from `EntityManager` and want to inject it into your service, this package covers that too. The principle is the same, and for more insight about this, you can check the package documentation at [dot-dependency-injection](https://docs.dotkernel.org/dot-dependency-injection/). --- title: "Disambiguation: Dotkernel 1 and Dotkernel 3" description: "Clarifies what Dotkernel 1 and Dotkernel 3 are, how they differ architecturally, and which version is meant when someone simply says 'Dotkernel'." author: "Gabi DJ" date_published: "2017-04-24" canonical_url: "https://www.dotkernel.com/dotkernel/disambiguation-dotkernel-1-and-dotkernel-3/" category: "Dotkernel" language: "en" --- # Disambiguation: Dotkernel 1 and Dotkernel 3 ## TL;DR Dotkernel 1 is the original PHP Application Framework built on Zend Framework 1 with an MVC architecture, released in 2010 and now in bugfix-only mode at version 1.8 LTS. Dotkernel 3 is a newer collection of PSR-7 middleware applications built on the Zend Expressive microframework and Zend Framework 3 components, implementing PSR-1, PSR-2, PSR-4, PSR-7, and PSR-11. Since Dotkernel 3's release, the unqualified name "Dotkernel" refers to Dotkernel 3, while Dotkernel 1 is always referenced explicitly. ## What Is the Meaning Behind 'Dotkernel'? The name **Dotkernel** symbiotically combines the string **Dot,** as a representation of the Internet, and **Kernel**, the quintessential components of any IT application. In other words, **Dotkernel** aims to become the starting point for development Internet applications and hence ensure increased development productivity and run-time performance. ## What Was Dotkernel 1? Dotkernel 1 was a ***PHP* *Application Framework***, built on top of Zend Framework 1 (ZF1). It had the first public release in July 2010. It was tightly coupled with **Zend Framework 1** and adds a set of custom or external features (such as Router, Template Engine, etc.). It was composed of **Zend Framework 1** and a set of custom or external features (such as Router, Template Engine, etc.). Dotkernel 1 architecture was based on **MVC**. The latest version is **1.8 Long Term Support**. It will not be getting any new releases or bugfixes because Zend Framework 1 is also not supported. If you are still using either Dotkernel 1 or Zend Framework 1, you need to refactor your code to the [Dotkernel Headless Platform](https://docs.dotkernel.org/headless-documentation/). ## What Is Dotkernel? A **collection** of PSR-15 Middleware applications built on top of the [**Mezzio**](https://docs.mezzio.dev/mezzio/v3/getting-started/quick-start/) microframework. It is composed of a set of custom and extended [**Laminas**](https://docs.laminas.dev/) components. Dotkernel architecture is based on **Middleware**. Dotkernel implements the following PSR's, where applicable: PSR-7, PSR-11, PSR-15, PSR-3, PSR-4, PSR-6, PSR-13, PSR-14, PSR-17, PSR-18, PSR-20. Currently, there are three applications: - API - Admin - Queue ## Dotkernel = Dotkernel 1 or the new Dotkernel? In posts older than 2017 **Dotkernel 1** was referred to as **Dotkernel** because it was the only Dotkernel version. Since the release of newer versions, we have dropped the number at the end, so currently we refer to our platform as 'Dotkernel'. --- title: "Doctrine cache using symfony/cache" description: "How to enable and configure the dotkernel/dot-cache component, a wrapper around symfony/cache, to cache Doctrine's result, metadata, query, and hydration data in Dotkernel Admin." author: "MarioRadu" date_published: "2024-02-27" canonical_url: "https://www.dotkernel.com/dotkernel/doctrine-cache-using-symfony-cache/" category: "Dotkernel" language: "en" --- # Doctrine cache using symfony/cache ## TL;DR Caching stores data the first time it's requested so that later requests can be served from the cache instead of the original, slower source, which improves response times. This article, a follow-up to an earlier caching article, shows how to enable the dot-cache component, a wrapper around symfony/cache, in Dotkernel Admin. It covers the array and filesystem storage adapters, configuring Doctrine's four cache types (result, metadata, query, hydration), and marking entities and queries as cacheable. When it comes to web development, performance is one of the critical elements that influence the success of an application. Developers focus on improving response times and overall speed to enhance the user experience. When a user visits a website or interacts with a web application, various resources such as images, scripts, and database queries are requested from the server. Retrieving these resources can sometimes be time-consuming, especially if they require complex processing or querying a database. To speed up this process and improve overall performance, developers implement caching mechanisms. When data is first requested, it's stored in a cache. Then, when subsequent requests for the same data are made, the application can retrieve it from the cache instead of fetching it from the original source. This reduces the time it takes to serve the content to the user because accessing data from the cache is typically much faster than retrieving it from the original source. > This article is a follow-up to the [previous article](https://www.dotkernel.com/how-to/doctrine-cache-in-mezzio-and-dotkernel/) where we tackled the caching topic. ![](/uploads/article/sdasdadsa.drawio.png) In this article our focus will be on enabling the [dot-cache](https://packagist.org/packages/dotkernel/dot-cache) component and effectively implementing caching in [Dotkernel Admin](https://github.com/dotkernel/admin/). ## Installation Run the following command in your project directory: ```bash composer require dotkernel/dot-cache ``` After installing, add the `DotCacheConfigProvider::class` class to your configuration aggregate (config/config.php). Before continuing with the configuration process, it helps to know a few things about how and where the data is stored. The [dotkernel/dot-cache](https://packagist.org/packages/dotkernel/dot-cache) component is a wrapper that sits on top of [symfony/cache](https://packagist.org/packages/symfony/cache). It currently supports two adapters and can store data in two distinct locations: - array - stores data in-memory - filesystem - stores data on local disk files 1. Storing data in-memory is the fastest and sometimes the cheapest caching mechanism, but it also comes with down-sides. Storing everything in RAM memory is not the best idea when your application is running on a low memory system. In this case you should consider using the filesystem mechanism. 2. The second caching mechanism involves storing data into files on the local disk, known as the filesystem option. While this option may be slightly slower than the first one, it provides a more persistent storage solution. Feel free to explore and use other adapters from [symfony/cache](https://packagist.org/packages/symfony/cache) by checking the [official documentation](https://symfony.com/doc/current/components/cache.html#advanced-usage). ## Configuration In `config/autoload/doctrine.global.php`, in the `doctrine.configuration.orm_default` key add the following entry: ```php 'result_cache' => 'filesystem', 'metadata_cache' => 'filesystem', 'query_cache' => 'filesystem', 'hydration_cache' => 'array', 'second_level_cache' => , ], ``` Next, under the `doctrine` key add the following items: ```php 'cache' => , 'filesystem' => , ], ``` The result is that the metadata and query cache will be stored in the `data/cache/doctrine` folder and the hydration cache will be stored in-memory. Each system is unique, requiring customized configurations. Make sure to identify the specific configuration requirements for your application. Doctrine cache is divided into 4 different types: - `result_cache` - `metadata_cache` - `query_cache` - `hydration_cache` ### Result Cache The result cache can be used to store the results of your queries, enabling Doctrine to avoid querying the database or hydrating the data again after the initial retrieval. ### Metadata Cache Parsing your class metadata on every request is inefficient. Instead, it's advisable to cache this information using one of the available cache adapters. ### Query Cache In a production environment, it's strongly recommended to cache the resulting DQL query into its SQL equivalent. Since the query doesn't change unless the DQL query itself changes, it's unnecessary to parse it multiple times. ### Hydration Cache Doctrine hydration cache is a feature that stores the results of data hydration, which is the process of converting raw database data into usable objects or arrays. By caching these results, it avoids repeating the hydration process for repeated queries, improving performance. ## How to Use To enable caching for entities, you need to add the `#` attribute like in the following example: ```php # # # class Admin extends AbstractEntity implements AdminInterface { } ``` For further details about the cache mode please refer to the [official documentation](https://www.doctrine-project.org/projects/doctrine-orm/en/latest/reference/second-level-cache.html). When querying data, you can have Doctrine cache your results. You do this by calling the `setCacheable` method on the query builder. ```php $this->getQueryBuilder() ->select('admin') ->from(Admin::class, 'admin') ->setCacheable(true) ->getQuery() ->getResult(); ``` Caching is not limited to entities alone. Objects can be cached too. Check the [basic cache usage](https://symfony.com/doc/current/components/cache.html#basic-usage-psr-6) for this purpose. In conclusion, cache plays a vital role in optimizing system performance and improving user experience by storing frequently accessed data. As technology continues to evolve, caching mechanisms will remain an integral part of modern computing architectures, driving faster access to data and smoother user interactions across various digital platforms. --- title: "Doctrine enum implementation in Dotkernel" description: "How Dotkernel adopted Doctrine ORM 3.2's EnumType support to replace loosely-enforced string-based status columns with PHP enums backed by a custom DBAL type." author: "Florin Bidirean" date_published: "2024-11-05" canonical_url: "https://www.dotkernel.com/dotkernel/doctrine-enum-implementation-in-dotkernel/" category: "Dotkernel" language: "en" --- # Doctrine enum implementation in Dotkernel ## TL;DR Doctrine ORM 3.2.0 added EnumType columns, building on the enum type introduced in PHP 8.1, and Dotkernel now implements this on both the PHP and database sides. The article contrasts Dotkernel's old string-based flag columns (like `User->Status`) with a new setup that uses custom PHP enums paired with a DBAL type extending `AbstractEnumType`. The new approach creates an explicit, enforced link between the PHP code and the database column values, at the cost of needing to update both sides whenever the value set changes. ## Doctrine's Approach The update introduces the detection of `enumType` and `options.values` from a property with `type: Types::ENUM`. [This PR](https://github.com/doctrine/orm/pull/11666) discusses the update and links to several older relevant issues. ### Old Setup ```php #[Entity] class Card { #[Id] #[GeneratedValue] #[Column] public int $id; #[Column( type: Types::ENUM, enumType: Suit::class, options: ['values' => ['H', 'D', 'C', 'S']], )] public Suit $suit; } ``` ### New Setup ```php #[Entity] class Card { #[Id] #[GeneratedValue] #[Column] public int $id; #[Column(type: Types::ENUM)] public Suit $suit; } ``` Note that the type `Types::ENUM` part is still required if we want to have an actual `enum` column in MySQL/MariaDB. We still default to `Types::STRING` or `Types::INTEGER` for column types with a PHP enum, as this is the more portable solution and the safer default. ## Dotkernel's Approach ### Old Setup Dotkernel uses flags for columns like `User->Status`, but we resorted to the simpler `string` type. The obvious disadvantage is that you can't definitively enforce a set of values for a given column. Sure, the PHP can be set up to only use the agreed-upon set of values, but the database is independent from it. If you edit a value manually in the database, any string is accepted. The issue is the same on the side of the PHP code. If the developer adds a value with a typo, it's supported, but will not work as intended. The only advantage this setup has is the ability to easily add more values in the value set. This may be seen as a feature, but it invites bugs in the execution. Our old implementation defined the values like below, for the `User` entity. ```php public const STATUS_PENDING = 'pending'; public const STATUS_ACTIVE = 'active'; public const STATUSES = [ self::STATUS_PENDING, self::STATUS_ACTIVE, ]; ``` The column for the ORM was defined like this, as a simple string, with `pending` as its default value: ```php #[ORM\Column(name: "status", type: "string", length: 20)] protected string $status = self::STATUS_PENDING; ``` Obviously, the `getStatus` and `setStatus` also work with strings: ```php public function getStatus(): string { return $this->status; } public function setStatus(string $status): self { $this->status = $status; } ``` ### New Setup Thanks to the update of `doctrine/orm` to version 3.2.0, Dotkernel can now have a proper link between the PHP code and database values. Now the link between the PHP code and the database is explicit and enforced. Any update to the value set must be on both the PHP code and the database. Let's review how the update affects the `User` entity. In the next example, we show how to implement a value set using a custom enum. First, we define our custom value set in `src/User/src/Enum/UserStatusEnum.php`. ```php namespace Api\User\Enum; enum UserStatusEnum: string { case Active = 'active'; case Pending = 'pending'; } ``` We need to create `src/User/src/DBAL/Types/UserStatusEnumType.php` to process the new values for the `status` column. `AbstractEnumType` must be extended by any future custom enum type. ```php namespace Api\User\DBAL\Types; use Api\App\DBAL\Types\AbstractEnumType; use Api\User\Enum\UserStatusEnum; class UserStatusEnumType extends AbstractEnumType { public const NAME = 'user_status_enum'; protected function getEnumClass(): string { return UserStatusEnum::class; } public function getName(): string { return self::NAME; } } ``` If you create your own enum types, make sure to update the `NAME` constant and the value returned by `getEnumClass`. Let's register the custom type in `config/autoload/doctrine.global.php` under the `types` key: ```php 'types' => [ [...] UserStatusEnumType::NAME => UserStatusEnumType::class, [...] ], ``` The filtering is updated in `src/User/src/InputFilter/Input/StatusInput.php`: ```php $this->getFilterChain() ->attachByName(StringTrim::class) ->attachByName(StripTags::class) ->attach(fn($value) => $value === null ? UserStatusEnum::Active : UserStatusEnum::from($value)); $this->getValidatorChain() ->attachByName(InArray::class, [ 'haystack' => UserStatusEnum::cases(), 'message' => sprintf(Message::INVALID_VALUE, 'status'), ], true); ``` The above ensures that the new `UserStatusEnum` class is used for the `status` column updates. The `User` entity uses the new `UserStatusEnum` class. ```php #[ORM\Column(type: 'user_status_enum', options: ['default' => UserStatusEnum::Pending])] protected UserStatusEnum $status = UserStatusEnum::Pending; ``` The `status` getter and setter are also updated: ```php public function getStatus(): UserStatusEnum { return $this->status; } public function setStatus(UserStatusEnum $status): self { $this->status = $status; } ``` Dotkernel checks the user status during login in `src/User/src/Repository/UserRepository.php`. If the user is not activated, the login is rejected. ```php if ($clientEntity->getName() === 'frontend' && $result['status'] !== UserStatusEnum::Active) { throw new OAuthServerException(Message::USER_NOT_ACTIVATED, 6, 'inactive_user', 401); } ``` A new user is created using the `enum` type and `pending` as the default. ```php $user = (new User()) ->setDetail($detail) ->setIdentity($data['identity']) ->usePassword($data['password']) ->setStatus($data['status'] ?? UserStatusEnum::Pending); ``` Note the `status` column in the migration query which now looks like this: ``` $this->addSql(' CREATE TABLE user ( uuid BINARY(16) NOT NULL, identity VARCHAR(191) NOT NULL, password VARCHAR(191) NOT NULL, status ENUM(\'active\', \'pending\') DEFAULT \'pending\' NOT NULL, isDeleted TINYINT(1) NOT NULL, hash VARCHAR(64) NOT NULL, created DATETIME NOT NULL, updated DATETIME DEFAULT NULL, UNIQUE INDEX UNIQ_8D93D6496A95E9C4 (identity), UNIQUE INDEX UNIQ_8D93D649D1B862B8 (hash), PRIMARY KEY(uuid)) DEFAULT CHARACTER SET utf8mb4'); ``` The difference for the migration query is for the `status` column, highlighted below: ``` old setup: status VARCHAR(20) NOT NULL new setup: status ENUM(\'active\', \'pending\') DEFAULT \'pending\' NOT NULL ``` ## Conclusions The old setup used in the Dotkernel applications worked fine, but the limitations were clear as day. There was: - No enforcement of the value set. - No link between the PHP code and the database. The new setup solves both issues, ensuring more consistent flag management for your classes. ## Resources - [Dotkernel API Pull Request](https://github.com/dotkernel/api/pull/339/files) - [Doctrine Pull Request](https://github.com/doctrine/orm/pull/11666) - [PHP Enumerations](https://www.php.net/manual/en/language.enumerations.overview.php) --- title: "Dotkernel Light - Starting with Mezzio microframework and Laminas components" description: "Dotkernel Light is a stripped-down version of Dotkernel Frontend built on Mezzio and Laminas components, keeping only routing, templating, error handling, and tests, for a gentler learning curve." author: "Florin Bidirean" date_published: "2024-10-03" canonical_url: "https://www.dotkernel.com/dotkernel/dotkernel-light-starting-with-mezzio-microframework-and-laminas-components/" category: "Dotkernel" language: "en" --- # Dotkernel Light - Starting with Mezzio microframework and Laminas components ## TL;DR Dotkernel Light is a version of Dotkernel Frontend that includes only the bare-bones essentials. It's built on the Mezzio microframework using Laminas components, and is designed as a presentation site, a fast-start introduction to Mezzio, or a clean starting point for a project where you want full control over functionality. ## Goal Dotkernel Light is designed to be a fast-start example of using the Mezzio microframework, as well as an entry-level version of Dotkernel Frontend. Its purpose is to present the newbie developer with as few moving parts as possible, while also giving the more advanced developer a starting point with full control of the platform's functionality. Light retains the modern architecture of Mezzio microframework and several Laminas components used in Dotkernel Frontend. The low number of out-of-the-box components encourages active exploration of the functionality required by your application - you add only the packages your application needs. ## Components and functionality Dotkernel Light is a stripped-down version of Dotkernel Frontend. Like Frontend, it is built on top of Mezzio microframework using Laminas components, but with limited features and a lower number of packages, which makes the learning curve of working with the repo considerably gentler. ### Functionality retained - Routing - Templating - Error handling - Tests and code quality checks ### Items removed compared to Frontend - Doctrine and all database-related stuff - Sessions/Cookies/Flash messages - Authentication/Authorization - Dependency Injection - Mail-related stuff - Navigation - CORS - Forms/Validators/InputFilters - User module - Contact module - Plugin module - CSS/JS code no longer in use due to the above module removals - Instructions from README.md that are no longer needed ### Packages no longer required - dotkernel/dot-authorization - dotkernel/dot-data-fixtures - dotkernel/dot-dependency-injection - dotkernel/dot-flashmessenger - dotkernel/dot-mail - dotkernel/dot-navigation - dotkernel/dot-rbac-guard - dotkernel/dot-response-header - dotkernel/dot-session - laminas/laminas-form - laminas/laminas-i18n - mezzio/mezzio-authorization-rbac - mezzio/mezzio-cors - ramsey/uuid-doctrine - roave/psr-container-doctrine - mezzio/mezzio-tooling - rector/rector ## Resources - Dotkernel Light GitHub repository: https://github.com/dotkernel/light - Working demo of Dotkernel Light: https://light.dotkernel.net/ - Dotkernel Light documentation: https://docs.dotkernel.org/light-documentation/ - Laminas Project: https://getlaminas.org/ - Documentation of Mezzio: https://docs.mezzio.dev/ --- title: "Dotkernel Light: the best choice for your presentation site" description: "A walkthrough of using Dotkernel Light to build a simple presentation site: adding new pages, managing assets, and configuring Twitter/OpenGraph cards, the top menu, and the footer." author: "Florin Bidirean" date_published: "2024-10-14" canonical_url: "https://www.dotkernel.com/dotkernel/dotkernel-light-the-best-choice-for-your-presentation-site/" category: "Dotkernel" language: "en" --- # Dotkernel Light: the best choice for your presentation site ## TL;DR Dotkernel Light is a lightweight starting point for a project when you want full control over its functionality, and it grows into something more complex as you add packages. It comes with routing, templating, error handling, and tests/code quality checks out of the box, but strips out everything a presentation site doesn't need - database, sessions/cookies/flash messages, auth, dependency injection, mail, navigation, CORS, forms, the user/contact/plugin modules. ## What's included vs. removed | Included out of the box | Removed (not needed for a presentation site) | |---|---| | Routing | Everything related to the database | | Templating | Sessions/Cookies/Flash messages | | Error handling | Authentication/Authorization | | Tests and code quality checks | Dependency Injection | | | Mail related stuff | | | Navigation | | | CORS | | | Forms/Validators/InputFilters | | | User module | | | Contact module | | | Plugin module | ## Adding new pages 1. Add an `Action` function for the page in `src/Page/src/Controller/PageController.php`, for example: ```php public function examplePageAction(): ResponseInterface { return new HtmlResponse( $this->template->render('page::example-template') ); } ``` The URL for this example page would be `/page/example-page`. 2. Create the matching template in `src/Page/templates/page/` - for the example above, `src/Page/templates/page/example-template.html.twig`. Put the page copy inside the `content` block: ```twig {% extends '@layout/default.html.twig' %} {% block title %}Page Title{% endblock %} {% block page_title %}{% endblock %} {% block content %}

Add title here!

Add cool content here!
{% endblock %} ``` Make sure to check the header for any fonts your content requires. 3. Place assets under `src/App/assets/`, in the default folders: - `src/App/assets/fonts` - `src/App/assets/images` - `src/App/assets/js` - `src/App/assets/scss` Make sure `npm` is installed and running during updates with `npm run watch`, or run `npm run prod` after edits are completed. ## Optional items ### Twitter and OpenGraph cards To promote pages on other platforms, edit the header section in `src/App/templates/layout/default.html.twig`, where the Twitter (X) and OpenGraph cards are placed. Update all items based on your page content. - `{{ url('home') }}` generates the homepage URL, and the same pattern is used for other pages, as in the canonical URL block: `{% block canonical %}{{ url(routeName ?? null) }}{% endblock %}` (the `block` is present to handle not-found pages, e.g. mistyped URLs). - An image referenced as `{{ url('home') }}images/app/My-image.png` is found at `public/images/app/My-image.png`, copied there by the `npm` script from `src/App/assets/images/PHP-REST-API.png`. ```html ``` ### Top menu This menu is displayed on all pages, in the header. Edit it in `src/App/templates/layout/default.html.twig`, under `id="navbarHeader"`: ```html ``` You can replace the `nav-item` class for the `li` elements with `button-border` for a link that looks more like a button. ### Footer To edit the footer on all pages, search for `