--- title: "Listen for Android install referrer" description: "Android market broadcasts an intent containing referrer information at install time, before the app is opened, which can be used for install tracking." author: "n3vrax" date_published: "2011-07-24" canonical_url: "https://www.dotkernel.com/android/listen-for-android-install-referrer/" category: "Android" language: "en" --- # Listen for Android install referrer ## Getting Referrer Data at Install Time Android market sends information at the moment of app install, delivered as a broadcasted intent by Android market at install time - even before the app is opened for the first time. This can be used to create custom links to an Android application, including bits of information about the referrer, sent directly to the app for processing at install. It can be a simple and accurate solution for mobile app install tracking, among other uses. ## FAQ **Q: Does Android send information when the app is installed?** A: Yes. Android market broadcasts an intent containing referrer information at the moment the app is installed. **Q: When is this referrer information available to the app?** A: It's delivered as a broadcasted intent at install time, before the app is ever opened. --- title: "Multiple broadcast receivers in the same app, for the same action" description: "Using multiple broadcast receivers to listen separately for the same intent in the same Android app can lead to unexpected results, since one receiver may consume the broadcast and leave the others with nothing." author: "n3vrax" date_published: "2011-07-22" canonical_url: "https://www.dotkernel.com/android/multiple-broadcast-receivers-in-the-same-app-for-the-same-action/" category: "Android" language: "en" --- # Multiple broadcast receivers in the same app, for the same action ## The problem When multiple broadcast receivers are registered separately to listen for the same intent within the same Android app, this can lead to unexpected results: one broadcast receiver might consume the broadcasted intent, leaving the others with nothing to receive. This can happen when using 3rd party libraries that define their own broadcast receivers alongside an app's own receivers. ## The approach A solution for this kind of problem is a code snippet inspired by the way Admob for Android solves this, as shown in Admob's own documentation, using meta-data in the manifest file. ## FAQ **Q: What problem does this article address?** A: When multiple broadcast receivers are registered separately to listen for the same intent in the same Android app, this can lead to unexpected results: one broadcast receiver might consume the broadcasted intent, leaving the others with nothing to receive. **Q: When is this issue most likely to occur?** A: This can happen when you use 3rd party libraries that already define their own broadcast receivers alongside your app's own receivers. ## Resources - [Admob App Download Tracking documentation](http://developer.admob.com/wiki/Android_App_Download_Tracking) --- 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 [ /* ... */ ]; } 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) 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 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. ## 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 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). ## FAQ **Q: What is a ConfigProvider in PHP?** A: It is a class that is part of an application's bootstrap process: a class or callable that returns configuration data telling the platform which middleware should run, in what order, and sometimes under what conditions. **Q: What does the ConfigProvider return in the Laminas/Mezzio ecosystem?** A: In the Laminas/Mezzio ecosystem, it's literally an array of configuration, settings, or anything else the application needs, and each module or package may contain its own ConfigProvider returning middleware pipeline configuration, dependency injection mappings, and request handlers. **Q: What is the difference between 'factories' and 'invokables' in the dependencies array?** A: `factories` will have the factory build the service, while `invokables` will use `new` directly. You can also use `aliases` to redirect to another service name and `delegators` to wrap the original service. **Q: How does the ConfigProvider get used during application bootstrap?** A: It is automatically picked up by the framework during bootstrap: all ConfigProviders are merged into one array, the configuration array is read, each item is resolved via `$app->pipe()`, the error-handling middleware is placed last in the pipeline, and at runtime Laminas Stratigility iterates over the pipeline in the order it was registered. **Q: Are new ConfigProviders auto-discovered in Dotkernel?** A: Dotkernel is an exception to the usual auto-discovery rule: new ConfigProviders have to be added manually in `config/config.php`, because all the initial ConfigProviders required to install the applications are already injected. **Q: What are the benefits of using a ConfigProvider?** A: Benefits include centralized setup instead of hardcoded bootstrap code, modularity so each package can ship its own config, container-friendliness with DI containers like Laminas ServiceManager, PHP-DI or Pimple, standardized service definitions, environment-agnostic configuration for dev/test/prod, and better testability of the pipeline setup. ## 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`. ## FAQ **Q: What is the request lifecycle?** A: 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. **Q: What happens at the entry point of a request?** A: The application bootstraps and loads configuration to create the Mezzio application instance, registers factories, aliases and delegators in the service container, reads all available routes with their allowed request methods and registers them (managed by FastRoute), and loads the predefined order of middleware in the pipeline. **Q: How does routing work in a Mezzio-based application?** A: FastRoute matches the incoming URL and method against the registered routes, for example matching a GET request to `/page/about` against the `GetPageViewHandler` handler under the route name `page::about`. **Q: What happens during handler invocation?** A: The matched route name is extracted from the request attribute and passed to the renderer, using code similar to `$template = $request->getAttribute(RouteResult::class)->getMatchedRouteName();`, after which the handler executes the custom business logic. **Q: What happens during template rendering?** A: Twig loads the matched template file, applies the layout it extends, renders its blocks, and includes any partials, producing the final HTML output. **Q: How is the response created and returned to the browser?** A: An `HtmlResponse` is created with a status code, headers, and the rendered HTML body. It then flows back through the middleware stack in reverse (the response pipeline), where middleware can modify headers, cookies, or compress content, before the response emitter sends the final response back to the browser as HTTP 20x/30x, 40x, or 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. ## FAQ **Q: What is middleware?** A: Middleware is code that exists between the request and response, and which can take the incoming request, perform actions based on it, and either complete the response or pass delegation on to the next middleware in the queue. **Q: What is the purpose of middleware?** A: 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. **Q: What can middleware be used for?** A: Middleware can be used for purposes such as A/B testing, debugging, caching, CORS, authentication (HTTP Basic Auth, OAuth 2.0, OpenID), CSRF protection, rate limiting, referrals, and IP restriction. **Q: What interface must PHP middleware implement to be PSR-15 compliant?** A: According to PSR-15, a compliant middleware must implement `Psr\Http\Server\MiddlewareInterface`, which requires a `process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface` method. **Q: How does middleware get called within the application pipeline?** A: The application pipeline defines the execution flow: the request passes through the middleware one by one, in the order they are placed. If control passes through all middleware successfully, execution is passed to your custom code, which generates a response, and execution then passes back through the middleware in reverse order. If execution is terminated before reaching your custom code (e.g. via an exception), the response is generated by the last middleware reached. **Q: What is a practical, real-world example of middleware?** A: A simple example is enhancing a request with the user's IP for logging purposes or geographical reporting. The request first passes through the IP middleware, which enhances the request with the user's IP and other relevant data, then control passes to the custom handler that processes the request and returns a response. The flow continues in reverse, back through the IP middleware, which can change the output before it's returned to the user. ## 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: "Aptana - set SVN keywords" description: "How to set the svn:keywords property (e.g. Id) for a file in Aptana, so SVN replaces the keyword marker with commit metadata." author: "Teo" date_published: "2011-04-04" canonical_url: "https://www.dotkernel.com/best-practice/aptana-set-svn-keywords/" category: "Best Practice" language: "en" --- # Aptana - set SVN keywords ## Overview In Aptana it's very simple to set the svn:keywords property for a file. For example, to set the svn keyword property `Id`: ## Steps 1. In the file where the svn keyword property should be added, write `$Id$`. 2. Right click on the file, then follow Team -> Set Property... (Note: "Set Property..." will not be active if the file hasn't first been added to SVN via Team -> Add to Version Controller). 3. Select `svn:keywords`, and write `Id` in the text field. When the SVN commit of the file is made, the `$Id$` keyword will be replaced with text containing the file's SVN metadata, in a specific format. ## FAQ **Q: How do you set the svn:keywords property for a file in Aptana?** A: Write the keyword marker (for example `$Id$`) in the file, then right click the file and follow Team -> Set Property..., select `svn:keywords`, and write `Id` in the text field. **Q: Why is "Set Property..." not active when I right click the file?** A: Set Property... will not be active if the file hasn't first been added to SVN. Use Team -> Add to Version Controller before trying to set the property. **Q: What happens to the $Id$ keyword after an SVN commit?** A: After the SVN commit of the file, the `$Id$` keyword is replaced with text containing the file's SVN metadata, in a specific format. ## Resources - [svn:keywords property documentation](http://svnbook.red-bean.com/en/1.4/svn.advanced.props.special.keywords.html) --- 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. ## Facets of Software Security There are many potential ways a hacker can access code or 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. ## The Tenets of Software Security in Dotkernel Headless Platform Dotkernel aims 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. ## Form Input Validation Never trust that user input is correct by passing it directly into business logic. By defining the configuration for an input filter, a field's presence and type are both ensured. Dotkernel API uses laminas/laminas-inputfilter for this purpose. Dotkernel Admin additionally uses laminas/laminas-form, which contains a thin layer of objects representing form elements, an InputFilter for each input (or custom validators), and methods for binding data to and from the form. laminas-form integrates with the Laminas Security Ecosystem: laminas-escaper, laminas-validator, laminas-session, and laminas-filter. ## Content Negotiation Content negotiation is used in RESTful APIs so client and server agree on the format and language of exchanged data. Dotkernel API handles this via a middleware configured in `config/autoload/content-negotiation.global.php`, using the `Content-Type` and `Accept` HTTP request headers, and returning `application/json` or `application/hal+json` data formats. ## Cross-Origin Resource Sharing CORS is a browser security mechanism controlling how web pages can request resources from a different domain. In Dotkernel API, CORS is handled by mezzio/mezzio-cors and configured in `config/autoload/cors.local.php`. It starts detecting the proper `cors` configuration whenever it detects a `cors preflight`, validating the call using configuration items: origins, headers, max age, and credentials. > When configuring your pipeline, make sure to add the CorsMiddleware BEFORE the RouteMiddleware. ## Role-Based Access Control RBAC manages access to resources by assigning roles to user types, which are in turn assigned to users requiring a certain level of access. Dotkernel API uses mezzio/mezzio-authorization-rbac for this purpose, with several predefined roles configurable in `config/autoload/authorization.global.php`. ## Demo Credentials Demo credentials are provided in Dotkernel API for convenience, to allow easy testing of the installation. > It is important to update or remove these accounts in your production environment. ## Error Reporting Endpoint and ErrorReportingTokens The error reporting endpoint provides a reliable channel through which 3rd-party developers can report issues directly. Dotkernel API has a dedicated `/error-report` endpoint for this, using an `ErrorReportingToken` set up in `config/autoload/error-handling.global.php`. ## OpenAPI Documentation OpenAPI documentation (formerly Swagger) provides a standardized, machine-readable way to describe API requests and responses. It's critical for developer efficiency (streamlines front/back-end communication, allows mock servers before the backend is implemented), reliability (auto-generated docs, easier testing), and integration (tools like Postman and Codegen libraries). Dotkernel API implements zircote/swagger-php to provide 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 Composer, and there is a tangible risk of exposing an application through insecure dependencies. Dotkernel API has regular checks for vulnerable and outdated packages, including transient dependencies. > Always use dependencies from reliable sources and keep them updated to their latest version. ## OAuth2 Security OAuth 2.0 is a secure authorization framework letting one application access resources on behalf of a user without requiring the user's password, an industry standard for web, mobile, and API-based systems. Dotkernel API uses mezzio/mezzio-authentication-oauth2 for OAuth2 authentication. The package itself is secure, but it must be used properly: - Replace or update the default `admin` and `frontend` clients on production. - Update the `access` and `refresh` tokens to match your application's requirements (defaults are one day for access, one month for refresh). - Never commit any local keys generated by `./vendor/bin/generate-oauth2-keys`, since they verify the transmitted JWTs. ## Session and Cookie Settings Sessions and cookies store data between HTTP requests, such as login information, preferences, or user behavior tracking. Dotkernel configures cookies in `config/autoload/session.global.php`, which contains parameters that must be revised and adapted: - `session_config.cookie_httponly` - `session_config.cookie_samesite` - `session_config.cookie_secure` ## JavaScript Dependencies JavaScript has its own dependencies, usually installed via npm or yarn. The JavaScript ecosystem has recently been attacked by hackers targeting several widely used npm packages with billions of total uses. Dotkernel uses npm to handle JavaScript dependencies, monitors the news for security issues, and uses packages from reliable sources. `npm audit` should still be used regularly to check for vulnerabilities. ## Other Security Considerations All components of Dotkernel Headless Platform have configuration files named `*.global.php`, `*.php.dist`, and `*.local.php`. Sensitive information must only go in `*.local.php` files, since they are ignored by the VCS by default. Development mode enables features like debug mode, cache clear, and error details, which should be hidden from production to avoid exposing sensitive data or code. The Laminas Continuous Integration GitHub Action is integral to Dotkernel API, running a matrix of static analysis, coding standards checks, and unit tests, most often triggered by commits. ## FAQ **Q: What are the main facets of software security to consider?** A: Software security spans many areas: 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, and human and organizational factors. **Q: How does Dotkernel handle form input validation?** A: Dotkernel API uses laminas/laminas-inputfilter to ensure a field is present and of the correct type. Dotkernel Admin additionally uses laminas/laminas-form, which provides form element objects, an InputFilter for each input (or custom validators), and methods for binding data to and from the form, integrating with laminas-escaper, laminas-validator, laminas-session, and laminas-filter. **Q: How does Dotkernel API handle content negotiation?** A: Content negotiation is handled via a middleware configured in the `config/autoload/content-negotiation.global.php` file. It uses the Content-Type and Accept HTTP request headers to negotiate with the client, returning application/json or application/hal+json data formats. **Q: How is CORS handled and configured in Dotkernel API?** A: CORS is handled by mezzio/mezzio-cors and configured in the `config/autoload/cors.local.php` file, validating calls using configuration items like origins, headers, max age, and credentials. When configuring the pipeline, the CorsMiddleware must be added before the RouteMiddleware. **Q: What should be done with the demo credentials before going to production?** A: Demo credentials are provided for convenience during installation testing, but it is important to update or remove these accounts in your production environment. **Q: What are the security recommendations around OpenAPI documentation?** A: You should not include sensitive information for your endpoints in the OpenAPI documentation, and you should not enable the documentation in a production environment. ## 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/mezzio-cors-implementation-in-dotkernel/) - [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: "Golden Rules of Professional PHP Coding" description: "A short list of practical rules for professional PHP development: error reporting settings, fixing warnings, marking hacks, single-responsibility functions, version control, and IDE usage." author: "admin" date_published: "2011-06-12" canonical_url: "https://www.dotkernel.com/best-practice/golden-rules-of-professional-php-coding/" category: "Best Practice" language: "en" --- # Golden Rules of Professional PHP Coding ## The Rules 1. Always use, in development and in staging, the highest error reporting level, and display_errors ON: ```php error_reporting(-1); ini_set('display_errors', 1); ``` 2. Fix every warning or notice that occurs. 3. Check regularly the server's error_log for notices/warnings. 4. Identify any temporary hack with a special mark, for example: ```php #@TODO masterpiece by @smartguy, to quick fix the division by zero ``` 5. Each function must do a single task. If it logs in the user and records the login in a stats table, create a separate function for the "record the login" part - maybe even a distinct class for stats. 6. Use a version control system. SVN is NOT dead. 7. Use an IDE, such as Aptana 2, Aptana 3, Eclipse, or Zend Studio. 8. Know your IDE: code snippets, code assist, integration with Zend Framework, SVN integration, bug tracker integration, and so on. ## FAQ **Q: What error reporting settings should be used in development and staging?** A: Always use the highest error reporting level and turn display_errors ON, for example with `error_reporting(-1);` and `ini_set('display_errors', 1);`. **Q: What should you do about warnings and notices?** A: Fix every warning or notice that occurs, and regularly check the server's error_log for notices and warnings. **Q: How should temporary hacks or quick fixes be marked in code?** A: Identify any temporary hack with a special mark, such as a `#@TODO` comment noting who added it and why. **Q: What is the rule about what a function should do?** A: Each function must do a single task. For example, if you're logging in a user and also recording that login in a stats table, create a separate function (or even a distinct class) for the stats recording, rather than combining both tasks in one function. **Q: What tools does the article recommend for professional PHP development?** A: It recommends using a version control system (noting that SVN is not dead) and using an IDE such as Aptana 2, Aptana 3, Eclipse, or Zend Studio, and knowing your IDE's code snippets, code assist, Zend Framework integration, SVN integration, and bug tracker integration. ## Resources - [Integrated development environment (Wikipedia)](http://en.wikipedia.org/wiki/Integrated_development_environment) - [Aptana 2 download](http://www.aptana.com/products/studio2/download) - [Aptana 3 download](http://www.aptana.com/products/studio3/download) - [Zend Studio](http://www.zend.com/en/products/studio/) --- 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 ## Redirect non-www to www To always redirect users to the www site (for example: `http://dotboost.com` to `http://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 ``` ## Redirect www to non-www If, instead, you want to redirect `http://www.dotboost.com` to `http://dotboost.com`, add the following lines instead: ```shell RewriteCond %{HTTP_HOST} ^www.dotboost.com RewriteRule ^(.*)$ http://dotboost.com/$1 ``` Replace `dotboost.com` with your site's domain in either case. ## FAQ **Q: How do I redirect a non-www domain to www using .htaccess?** A: Add `RewriteCond %{HTTP_HOST} ^dotboost.com` and `RewriteRule ^(.*)$ http://www.dotboost.com/$1` to your .htaccess file, right after `RewriteEngine On`, replacing dotboost.com with your own domain. **Q: How do I redirect a www domain to non-www instead?** A: Add `RewriteCond %{HTTP_HOST} ^www.dotboost.com` and `RewriteRule ^(.*)$ http://dotboost.com/$1` instead, again replacing dotboost.com with your own 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. ## Connecting to the database ```php $db = Zend_Db::factory('Pdo_Mysql', $dbConnect); ``` ## INSERT SQL: ```sql INSERT INTO user(email, password, firstName, lastName, active) VALUES ('$email', '$password', '$firstName', '$lastName', 1); ``` Zend_Db: ```php $data = array( 'email' => $email, 'password' => $password, 'firstName' => $firstName, 'lastName' => $lastName, 'active' => '1'); $db->insert('user', $data); ``` ## UPDATE SQL: ```sql UPDATE user SET password = '$password', firstName = '$firstName', lastName = '$lastName', accountUpdate = (accountUpdate +1) WHERE id = '$id' ``` Zend_Db: ```php $data = array('password' => $password, 'firstName' => $firstName, 'lastName' => $vlastname, 'accountUpdate' => new Zend_Db_Expr('accountUpdate+1')); $db->update('user', $data, 'id = '.$id); ``` ## DELETE SQL: ```sql DELETE FROM user WHERE id = '$id' ``` Zend_Db: ```php $db->delete('user', 'id = '.$id); ``` ## FAQ **Q: What are DML statements?** A: DML (Data Manipulation Language) statements are statements that change data values in database tables. There are 3 primary DML statements: INSERT, UPDATE, and DELETE. **Q: How do you insert a new row with Zend_Db?** A: Build an associative array of column names to values (e.g. email, password, firstName, lastName, active) and pass it to $db->insert('user', $data), which corresponds to an SQL INSERT INTO ... VALUES statement. **Q: How do you update rows with Zend_Db, including incrementing a column?** A: Build a $data array of the columns to update, using a Zend_Db_Expr for expressions such as incrementing accountUpdate (new Zend_Db_Expr('accountUpdate+1')), then call $db->update('user', $data, 'id = '.$id). **Q: How do you delete a row with Zend_Db?** A: Call $db->delete('user', 'id = '.$id), which is equivalent to the SQL statement DELETE FROM user WHERE id = '$id'. ## Resources - [Zend_Db series](http://www.dotkernel.com/dotkernel/sql-select-zend-db/) --- 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. ## Connecting to the database ```php $db = Zend_Db::factory('Pdo_Mysql', $dbConnect); ``` ## SELECT query - WHERE clause The following two classical SQL queries are equivalent - the first is a simple comma join, the second uses INNER JOIN - 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}') ``` Translated into 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 no column should be selected from the second table, the 3rd parameter of join() 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 the 3rd parameter is not written at all, 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)); ``` ## Debugging a query If you are not sure the correct query is being generated, echo it before fetching: ```php echo $select->__toString();exit; ``` ## FAQ **Q: What does Zend_Db provide?** A: Zend_Db and its related classes provide a simple SQL database interface for Zend Framework. To connect to a MySQL database, the Pdo_Mysql adapter is used via Zend_Db::factory('Pdo_Mysql', $dbConnect). **Q: How do you write a SELECT with a JOIN and a WHERE clause in Zend_Db style?** A: Use $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), which is equivalent to a classical SQL query using INNER JOIN. **Q: How do you join a table without selecting any of its columns?** A: Pass an empty string as the 3rd parameter of the join() method, e.g. ->join(array('b'=>'orders'), 'a.id = b.user_id', ''). **Q: What happens if the 3rd parameter of join() is omitted entirely?** A: If the 3rd parameter is not written, it will select all the fields from that joined table (equivalent to SELECT ..., b.* in SQL). **Q: How do you write a WHERE IN clause with Zend_Db?** A: Use ->where('aff_id IN (?)', array(1,2,3)) on the select object, equivalent to SQL's WHERE aff_id IN ('1','2','3'). **Q: How can you check that a Zend_Db select is generating the correct query?** A: Before fetching it, echo the query to visualize it: echo $select->__toString();exit; ## Resources - [Zend_Db](https://docs.laminas.dev/laminas-db/adapter/) - [What are returning the FETCH functions from Zend_Db](http://www.dotkernel.com/best-practice/sql-fetch-zend-db/) - [Subqueries with Zend_Db](http://www.dotkernel.com/best-practice/subqueris-with-zend-db/) - [INSERT, UPDATE, DELETE statements with Zend_Db](http://www.dotkernel.com/best-practice/iud-statements-with-zend-d/) --- 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. ## The SQL query ```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 ``` ## Connecting to the database ```php $db = Zend_Db::factory('Pdo_Mysql', $dbConnect); ``` ## Building the query in Zend_Db ```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'); ``` The `count_files` column is built by wrapping a nested `$db->select()` call inside a `Zend_Db_Expr`, correlated back to the outer table via `c.track_id = a.id`. ## FAQ **Q: What SQL techniques does this subquery example combine?** A: The example combines COUNT(), LEFT JOIN, and GROUP BY, selecting from 3 tables and counting rows from 2 different tables. **Q: How do you embed a subquery as a selected column in a Zend_Db select?** A: Wrap a nested $db->select() call inside a Zend_Db_Expr, building the subquery string with the outer table's correlated WHERE condition (e.g. c.track_id = a.id), as shown for the count_files column. **Q: How is the LEFT JOIN with a COUNT expressed in Zend_Db?** A: Use ->joinLeft(array('b'=>'track_courses'), 'a.id = b.track_id', array('count_courses' => 'COUNT(b.track_id)')) followed by ->group('a.id'). ## Resources - [Zend_Db series](http://www.dotkernel.com/dotkernel/sql-select-zend-db/) --- title: "SVN Export in a virtual host" description: "How to export the contents of an SVN repository into a virtual host directory using the svn export command." author: "Adrian" date_published: "2011-05-30" canonical_url: "https://www.dotkernel.com/best-practice/svn-export-in-a-virtual-host/" category: "Best Practice" language: "en" --- # SVN Export in a virtual host ## TL;DR `svn export` lets you export the contents of a repository into a virtual host directory. The commands should be run in a terminal (e.g. via Putty on Windows) on the target host, ideally using the domain's own user rather than root. ## Steps 1. Make sure Subversion is installed on the host by running `svn --version`. If you don't get a "command not found" message, it's installed; otherwise, install it. 2. Go to the directory where you want to export the contents of the repository (e.g. `cd /var/www/vhosts/example.com/httpdocs` or `cd /home/sitename/public_html`). 3. Run the export command: ```shell svn export repositoryUrl repositoryUrl ``` Where: | Parameter | Meaning | |---|---| | `-r revisionNumber` | Optional. Exports a specific revision. By default, the latest revision is used. | | `repositoryUrl` | The repository URL (e.g. `http://example.com/repos/project-name/trunk/`). Remember to add `/trunk/`, or change it appropriately for a branch or tag. | | `targetDirectory` - `./` | The current directory. | | `targetDirectory` - `./project-name` | Exports to the `project-name` subdirectory. | | `targetDirectory` - `/var/www/vhosts/example.com/httpdocs` | Exports to an absolute path. | | `--force` | Optional. By default SVN will not export into an existing directory; this overrides that. **Be careful, this option can overwrite files.** | 4. For more information, run `svn help export`. ## Examples ```shell svn export http://v1.dotkernel.net/svn/trunk ./ --force svn export -r 423 http://v1.dotkernel.net/svn/trunk ./ --force svn export http://v1.dotkernel.net/svn/trunk /var/www/vhosts/domain.com/httpdocs/dk ``` ## Fixing permissions afterward If the repository was exported using a different user (e.g. root), change the permissions back as root: ```shell chown -R siteuser.psacln /var/www/vhosts/example.com/httpdocs ``` ## FAQ **Q: How do you check if Subversion is installed on the host?** A: Run svn --version. If you don't get a "command not found" message, Subversion is installed; otherwise, you need to install it. **Q: What is the basic command to export a repository?** A: The command is svn export repositoryUrl targetDirectory, run from the host where you want to export the repository, ideally using the domain's user rather than root. **Q: What does the -r option do?** A: -r revisionNumber is optional and exports a specific revision; by default, the latest revision is used. **Q: What does the --force option do, and what is the risk?** A: By default SVN will not export into an existing directory; --force overrides this. Be careful, since this option can overwrite files. **Q: How do you fix file permissions if you exported the repository as a different user?** A: As root, run chown -R siteuser.psacln /var/www/vhosts/example.com/httpdocs to change the permissions back. --- title: "SVN keywords setup in PHP IDE ( Zend Studio)" description: "How to set SVN ignore, bug tracker, and svn:keywords properties per project in the Zend Studio PHP IDE." author: "admin" date_published: "2013-02-21" canonical_url: "https://www.dotkernel.com/best-practice/svn-keywords-setup-in-php-ide-zend-studio/" category: "Best Practice" language: "en" --- # SVN keywords setup in PHP IDE ( Zend Studio) ## TL;DR For better integration between SVN, the Zend Studio PHP IDE, and a bug tracker, a set of SVN properties must be set for each project. This article lists which properties to set and how. ## Steps 1. Right click on the **project**. 2. Go to **Team -> Set Propriety**. 3. Set `svn:ignore` so local settings aren't committed to the main repository: ``` Name: svn:ignore Propriety: *.project *.prefs .project cache .settings .buildpath *.ini ``` 4. Set up basic bug tracker integration: ``` Name: bugtracq:label Propriety: Tracker ID: ``` ``` Name: bugtraq:message Propriety: ``` 5. If using a public bug tracker (e.g. Mantis), also set: ``` Name: bugtraq:url Propriety: http://www.dotkernel.net/view.php?id=%BUGID% ``` For the properties above, apply them **only** to the project folder, **not** recursively. ## Final step (svn:keywords only) 1. Check **Apply property recursively to:**. 2. Select **All resources**. 3. Check **Use filtration by the resource name** and add mask: `*.php`. ## FAQ **Q: Why set these SVN properties on each project?** A: They provide better integration of SVN, your PHP IDE (Zend Studio), and a bug tracker of choice, and must be set for each project you have. **Q: What does the svn:ignore property do here?** A: It tells SVN to ignore local settings files such as *.project, *.prefs, .project, cache, .settings, .buildpath, and *.ini, since you don't want to commit your local settings to the main repository. **Q: How do you set up basic bug tracker integration?** A: Set the bugtracq:label property to "Tracker ID:" and bugtraq:message; if you have a public bug tracker such as Mantis, also set bugtraq:url to a URL pattern like http://www.dotkernel.net/view.php?id=%BUGID%. **Q: Should these properties be applied recursively?** A: No. For the properties above, apply them only to the project folder, not recursively. **Q: How is the svn:keywords property applied differently?** A: Check "Apply property recursively to:", select "All resources", then check "Use filtration by the resource name" and add the mask *.php. --- 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. ## Connecting to the database ```php $db = Zend_Db::factory('Pdo_Mysql', $dbConnect); ``` ## LIKE _ Return all ids that start with '1' and whose 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, starting with 'Fr' and ending with '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 that don't have exactly 2 digits (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' 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); ``` ## FAQ **Q: What do the LIKE wildcards _ and % mean?** A: The _ wildcard matches a single character, while % matches any string of any length, including zero length. **Q: Which SQL statements can use the LIKE condition?** A: LIKE allows pattern matching in the WHERE clause and can be used in any valid SQL statement: SELECT, INSERT, UPDATE, or DELETE. **Q: How do you build a LIKE query with Zend_Db?** A: Quote the column with $this->db->quoteIdentifier(), build the condition with $this->db->quoteInto("$col LIKE ? ", $pattern), and pass the resulting $where string into ->where() on a select, then run it with $this->db->fetchAll($select). **Q: How do you combine multiple LIKE conditions with OR?** A: Build the first condition with quoteInto, then append further ones with quoteInto("OR $col LIKE (?) ", $pattern), as in the example matching 'gallery' or 'folder' in the source field. **Q: How does NOT LIKE differ from LIKE?** A: NOT LIKE negates the pattern match - for example, id NOT LIKE '1_' returns ids that don't start with 1 or don't have exactly 2 digits, and NOT LIKE conditions can be chained with AND to exclude several patterns at once. --- 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. ## Available FETCH Methods Continuing the Zend_Db article series, this article stops at the FETCH methods found in Zend_Db_Adapter_Abstract: ```php array fetchAll (string|Zend_Db_Select $sql, ...) array fetchAssoc (string|Zend_Db_Select $sql, ...) array fetchCol (string|Zend_Db_Select $sql, ...) string fetchOne (string|Zend_Db_Select $sql, ...) array fetchPairs (string|Zend_Db_Select $sql, ...) array fetchRow (string|Zend_Db_Select $sql, ...) ``` To make it easier to follow, each example below shows the classical, old-style query first, followed by the equivalent query written in Zend_Db style. ## Connecting to the Database Initialize the connection to the MySQL database: ```php $db = Zend_Db::factory('Pdo_Mysql', $dbConnect); ``` ## Setting Up the Query Here is a SQL query that we want to fetch: ```sql $sql = "SELECT id, title FROM files"; $db->query($sql) ``` Here is the same query written in Zend_Db style: ```php $select = $db->select() ->from('files', array('id', 'title')) ``` Note: the old style of fetching shown below uses an older class. Here's what you need to know about its methods: - `query()` is similar to `mysqli_query()` from the Mysqli PHP extension - `next_record()` is similar to `mysqli_next_result()` from the Mysqli PHP extension - `f()` retrieves the value of the column specified as a parameter ## fetchAll Old style: ```php while($db->next_record()) { $a[] = array( 'id' => $db->f('id'), 'title' => $db->f('title') ); } ``` Zend_Db style: ```php $a = $db->fetchAll($select); ``` ## fetchAssoc Old style: ```php while($db->next_record()) { $a = array( 'id' => $db->f('id'), 'title' => $db->f('title') ); } ``` Zend_Db style: ```php $a = $db->fetchAssoc($select); ``` ## fetchCol Old style: ```php while($db->next_record()) { $a[] = $db->f('id'); } ``` Zend_Db style: ```php $a = $db->fetchCol($select); ``` ## fetchOne Old style: ```php $db->next_record(); $a = $db->f('id'); ``` Zend_Db style: ```php $a = $db->fetchOne($select); ``` ## fetchPairs Old style: ```php while($db->next_record()) { $a = $db->f('title'); } ``` Zend_Db style: ```php $a = $db->fetchPairs($select); ``` ## fetchRow Old style: ```php $db->next_record(); $a = array( 'id' => $db->f('id'), 'title' => $db->f('title') ); ``` Zend_Db style: ```php $a = $db->fetchRow($select); ``` ## FAQ **Q: What FETCH methods are available in Zend_Db_Adapter_Abstract?** A: The article covers fetchAll, fetchAssoc, fetchCol, fetchOne, fetchPairs, and fetchRow. **Q: What does fetchAll do compared to the old query style?** A: `$a = $db->fetchAll($select)` replaces the old-style loop that calls `next_record()` repeatedly and builds an array of associative rows using `f()` for each column. **Q: What does fetchRow return?** A: `$a = $db->fetchRow($select)` returns a single row as an associative array, replacing a single `next_record()` call followed by `f()` calls for each column. **Q: What does fetchOne return?** A: `$a = $db->fetchOne($select)` returns a single value, replacing a single `next_record()` call followed by one `f()` call. **Q: How do the old-style query(), next_record(), and f() methods relate to Mysqli?** A: `query()` is similar to `mysqli_query()`, `next_record()` is similar to `mysqli_next_result()`, and `f()` retrieves the value of the column specified as a parameter. --- 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. ## Why Use CURRENT_TIMESTAMP as a Default On a TIMESTAMP field that records date and time when inserting a new record, it is encouraged to use the CURRENT_TIMESTAMP constant as a DEFAULT value. Because when inserting a new row in the table, there is no need to specifically add the value for the date and time field, either by creating it from PHP code with the Date/Time functions or with MySQL's NOW() function: ```sql ALTER TABLE `user` CHANGE `dateCreated` `dateCreated` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP; ``` ## Automatically Updating with ON UPDATE CURRENT_TIMESTAMP CURRENT_TIMESTAMP is also a solution for updating date and time fields. Use the `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 Clause Combinations 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 in 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 the [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. ## FAQ **Q: Why use CURRENT_TIMESTAMP as a DEFAULT value for a date/time field?** A: Because when inserting a new row, there is no need to specifically set the date/time value yourself, either from PHP Date/Time functions or with MySQL's NOW() function. **Q: How do you make a field update its timestamp automatically on every UPDATE?** A: Add the ON UPDATE CURRENT_TIMESTAMP clause, for example: `ALTER TABLE `user` CHANGE `dateLogin` `dateLogin` TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP`. **Q: What happens if a TIMESTAMP column has neither a DEFAULT nor an ON UPDATE clause?** A: For the first TIMESTAMP field in the table, having neither clause is the same as DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP. **Q: What happens with a DEFAULT CURRENT_TIMESTAMP clause but no ON UPDATE clause?** A: The column gets the current timestamp as its default value but is not automatically updated afterward. **Q: Can more than one TIMESTAMP column default to CURRENT_TIMESTAMP in the same table?** A: No. Only one timestamp field in a table can be DEFAULT CURRENT_TIMESTAMP. --- 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. ## A Bit of History It all started with the announcement: Laminas MVC Is Retiring. 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. 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 - the 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. ## FAQ **Q: What is Laminas MVC being replaced by?** A: Mezzio microframework, built using Laminas components. It has gone through rigorous development and testing since being released in 2015, when it was known as Zend Expressive, before being renamed Mezzio. **Q: Why is maintaining legacy platforms a problem?** A: Maintaining legacy platforms over the long term is often costly and time-consuming, so every few years platform owners must consider migrating to a newer platform that offers modern architecture, an active community, easier development/expansion/maintenance, security improvements, and more reliable dependencies. **Q: What is the core architectural pain point with legacy MVC platforms?** A: The MVC architecture is obsolete, fit for monolithic websites. Today's and tomorrow's architecture is based on middleware, building headless platforms, websites, and microservices following the same coding approach. **Q: What steps does Apidemia's migration process involve?** A: A simplified task list: code audit & migration strategy; partial or full migration to Laminas or PSR-compliant frameworks like Mezzio or Symfony; refactoring and decoupling legacy modules; unit testing and CI/CD pipeline setup; and post-migration support and team training. **Q: Who offers this migration guidance?** A: Apidemia, who has used Zend Framework, Laminas MVC, and Mezzio for years and can analyze and perform the transfer of a legacy platform to Mezzio, offering faster execution times, increased security, faster development, and long-term reliability. ## 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: "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. ## FAQ **Q: Why is the team considering a switch from Postman to Bruno?** A: They want a reliable API testing client that is free, stores and shares endpoint collections easily with the team, and is fast and secure. This reflects a broader trend in the PHP community toward local-first, Git-native developer tools. **Q: What is the main architectural difference between Postman and Bruno?** A: Postman's free plan now only allows one user account, while Bruno offers a fully-offline experience based on shared `.bru` files, so there is no restriction on the number of developers using them. **Q: How does version control differ between the two tools?** A: Postman stores collections and handles version control in the cloud, forcing developers to stay online (though collections can be exported/imported via its UI). Bruno's `.bru` files can be saved directly in a Git repository and are version-controlled through Git like any other project file. **Q: How does performance compare between Postman and Bruno?** A: Bruno is the clear winner on performance: it uses much less RAM and is generally faster. Postman needs to regularly synchronize with the cloud and store its advanced features in RAM, which can introduce delays. **Q: Is Bruno more secure than Postman?** A: Postman offers Single Sign-On (SSO) and Role-Based Access Control (RBAC), which the team doesn't find useful for its workflow. Bruno's local files never leave the dev environment, which the article argues makes it more secure, especially for avoiding sharing client files with online tools. **Q: What's the overall conclusion on Postman versus Bruno?** A: 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 works offline, which the team considers more secure while also being generally faster, and it has become their de facto API client. ## 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. ## FAQ **Q: Why was this endpoint created?** A: When a Frontend client (e.g. Angular) running on the user's machine hits an error against the Dotkernel API - whether from an overnight API response change or a simple undefined variable - there is little that can be done from the client side, so this endpoint lets clients "write down" the error instead. **Q: How do I submit an error from the client?** A: Send a simple POST request to your Dotkernel API's `https://api.dotkernel.net/error-report` route, with a body such as `{ "message": "My awesome error!!!" }`. **Q: Where is the submitted error message stored?** A: By default, it is stored in a separate log file for Client, `/log/error-report-endpoint-log.log`, with the message saved alongside 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. ## FAQ **Q: What is content negotiation?** A: It's the act of a client and server agreeing on the format and language of the data they exchange, which is important for RESTful APIs since resources can support multiple representations. **Q: What does content negotiation ensure?** A: It ensures support for diverse clients (e.g. `Accept: application/json` or `Accept: application/xml`), data format flexibility for smaller responses (e.g. `Accept: application/msgpack`, a binary serialization), and language localization via headers like `Accept-Language: en-US`. **Q: Who decides the data format, the client or the server?** A: Either side technically can. In server-side negotiation, the server decides based on various factors, which can introduce erroneous assumptions and more complex implementation, forcing the client to adhere to server rules. In client-side negotiation, the client tells the server what format it prefers, which is more versatile and makes more sense. **Q: How can the preferred data format be communicated?** A: Via HTTP request headers (`Content-Type` and `Accept`) or via resource URI patterns, such as a file extension in the URL (e.g. `/record/47.json`) or an extra query parameter (e.g. `/record/47?format=json`). If the `Accept` header is not present, the server decides the response format. **Q: How does the quality factor (q) work in the Accept header?** A: The `Accept` header can list multiple accepted formats with a `q` value between 0 and 1 to express preference, e.g. `Accept: application/json,application/xml;q=0.9,*/*;q=0.8`. The server responds with the most preferred format it can satisfy, falling back further down the list if needed. **Q: How does Dotkernel API handle content negotiation?** A: 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 needed, and per-route content negotiation is also supported. ## 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 ## FAQ **Q: What is Dotkernel API?** A: It is a Zend Expressive 3 application aiming to help developers quickly and efficiently develop an API. **Q: What key libraries does Dotkernel API 1.0.0 use?** A: Among others, it's built on the `ezimuel/zend-expressive-api` skeleton, and uses `dotkernel/dot-annotated-services` for dependency injection, `dotkernel/dot-console` for console applications, `dotkernel/dot-errorhandler` for error logging, `dotkernel/dot-mail` for SMTP email, `zend-expressive-authentication-oauth2` for OAuth2 authentication, `zend-expressive-authorization-rbac` for role-based permissions, and `swagger-api/swagger-ui` for OpenAPI 3 documentation. **Q: What features does Dotkernel API 1.0.0 offer out of the box?** A: Secure authentication via OAuth2, two user roles (admin and member), where admins can manage any user account and members can manage only their own, plus OpenAPI 3 documentation with an interactive interface developers can use to integrate the 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. ## FAQ **Q: What does a client send to request authorization?** A: The client application sends a POST request to the backend with a JSON object containing `grant_type` (set to "password"), `client_id`, `client_secret`, `scope`, `username`/email, and `password`. **Q: What does the API return when authorization succeeds?** A: If the credentials are correct, the API returns a JSON object containing `token_type` ("Bearer"), `expires_in` (86400 seconds), an `access_token`, and a `refresh_token`. **Q: How do I use the access token in subsequent requests?** A: When sending API requests to an endpoint that requires authorization, include an Authorization header containing `"Bearer {access_token}"`, where `{access_token}` is the value returned 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'); ``` ## FAQ **Q: What are the three access levels for protecting an endpoint?** A: no-auth, where the resource can be accessed without authentication/authorization; authentication, where only authenticated users can access the resource; and authorization, where only authenticated AND authorized users can access it. **Q: Where do I configure access to the endpoints?** A: In `config/autoload/authorization.local.php`. If that file is missing from your application, locate its dist file `config/autoload/authorization.local.php.dist` and copy it as `config/autoload/authorization.local.php`, then look for the array under the `zend-expressive-authorization-rbac` config key. **Q: How does role inheritance work under the roles key?** A: In the article's example, admin inherits from no other role, member inherits from admin, and guest inherits from member. The article warns this exact setup is just a model and should not be used in live projects, because guests would end up having the same rights as admins. **Q: How do I control which routes a role can access?** A: Under the `permissions` key you define which routes are accessible to a role. In the article's example, a member has access to the routes named avatar, users, and user. **Q: What response codes are returned for authentication and authorization endpoints?** A: Endpoints requiring authentication return a 401 Unauthorized response if a valid Bearer token isn't present in the request headers. Endpoints requiring authorization return a 403 Forbidden response instead under the same condition. --- 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 is 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.org) | | First Release | 2012 | 2018 | | PHP Version | <= 8.2 | Shown via a dynamic Packagist badge (see the project repository for the current supported version) | | Architecture | MVC, Event Driven | Middleware | | OSS Lifecycle | Archived | Shown via a dynamic OSS Lifecycle badge (see the project repository for the current status) | | 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. ## FAQ **Q: What is the purpose of this comparison?** A: It highlights the differences between Laminas API Tools and Dotkernel API, and shows why Dotkernel API is a good alternative now that Laminas API Tools is archived. **Q: Which version of Dotkernel API does the comparison table refer to?** A: Dotkernel API V7. **Q: What architecture does each project use?** A: Laminas API Tools uses an MVC, event-driven architecture, while Dotkernel API uses a middleware architecture. **Q: What license does each project use?** A: Laminas API Tools is licensed under BSD-3, while Dotkernel API is licensed under MIT. **Q: How does Dotkernel API handle API versioning?** A: Instead of traditional versioning, Dotkernel API replaces it with Deprecations, using an evolution (API Evolution) strategy. **Q: What documentation options does each project support?** A: Laminas API Tools generates Swagger documentation automatically, while Dotkernel API supports manual Postman documentation as well as automated OpenAPI 3.0 (Swagger) documentation. --- 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). ## FAQ **Q: What is the error reporting endpoint for?** A: It lets frontend developers of an API report bugs and incorrect data processing back to the API in a secure, controlled way, which is especially useful for issues that don't show up as fatal errors in the API logs. **Q: How do you generate a token for error reporting?** A: Run `php ./bin/cli.php token:generate error-reporting`, then copy the resulting token into `config/autoload/error-handling.global.php`. **Q: What server-side requirements must be met for error reporting to work?** A: All required keys (`enabled`, `path`, `tokens`, `domain_whitelist`, `ip_whitelist`) must exist under `ErrorReportServiceInterface::class`, the feature must be enabled, `path` must have a value, `tokens` must contain at least one token, and at least one of `domain_whitelist`/`ip_whitelist` must have a value. **Q: What headers must the frontend application send?** A: The `Error-Reporting-Token` header with a valid stored token, and the `Origin` header set to the application's URL. **Q: What happens if a request fails validation?** A: The `checkRequest()` method checks the domain against `domain_whitelist` and the IP against `ip_whitelist`; if both checks fail, a `ForbiddenException` is thrown and the error message is not stored. **Q: How is the error reporting endpoint called?** A: By sending a POST request to the `/error-report` endpoint along with a valid token in the header. --- 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') ?? []; return new MailChimp($config ?? ''); } } ``` 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. ## FAQ **Q: Which library does this tutorial use to add MailChimp to Dotkernel API?** A: The tutorial uses drewm/mailchimp-api, installed with the command composer require drewm/mailchimp-api. **Q: Where do you place the MailChimp configuration file?** A: In config/autoload/mailchimp.global.php, a new configuration file created as part of Step 2. **Q: What does the MailChimpFactory class do?** A: It's a factory, created at src/App/src/MailChimp/Factory/MailChimpFactory.php, that reads the config from the container and returns an instance of DrewM\MailChimp\MailChimp. **Q: Where do you register the MailChimp factory so the application can use it?** A: In src/App/src/ConfigProvider.php, inside the getDependencies() method's factories array, by mapping MailChimp::class to MailChimpFactory::class, plus adding the corresponding use statements for MailChimp and MailChimpFactory. **Q: How do you use MailChimp once it's wired up?** A: By injecting MailChimp::class wherever it's needed, using @Inject. --- 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/). ## FAQ **Q: What is the OpenAPI Specification?** A: 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, typically described in YAML or JSON so users can quickly discover endpoints, request/response formats, security mechanisms and more. **Q: How does OpenAPI compare to Postman?** A: OpenAPI standardizes how endpoints and request/response models are described, automatically generates machine-readable documentation, lets you define the API specification before development starts, and improves collaboration across teams. Postman, by contrast, is used mainly to test an already-completed endpoint and has no real focus on standardized documentation or upfront design. **Q: Where do you document endpoints in Dotkernel API?** A: Each module (Admin, App, User) contains an OpenAPI.php file, where all endpoints from that module's RoutesDelegator.php must be documented, primarily describing the method, request and response. **Q: What core components does every OpenAPI description need?** A: OA\Info (basic project info like version and name), OA\Server (one or more target host URLs), OA\SecurityScheme (endpoint protection), OA\ExternalDocumentation (link and description for extended docs), and OA\Schema (describing an object or collection of objects). **Q: What generates the documentation file from the OpenAPI.php descriptions?** A: zircote/swagger-php, which uses the descriptions added in the OpenAPI.php files to build the documentation. The result can be listed in the command line or saved to a file in YAML or JSON format. **Q: How is the generated documentation rendered, and how do you test protected endpoints?** A: It can be rendered with Swagger UI, which lets you visualize and interact with the API's resources, or with Redoc, which lists the documentation in read-only mode. Because most endpoints are protected, testing them in Swagger UI requires generating an authentication token (AuthToken) matching the required privileges, then using the 'Try it out' button to fill in parameters/body and 'Execute' to send the request and see the response with its HTTP status code. --- 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 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. ## FAQ **Q: What causes the "No 'Access-Control-Allow-Origin' header" error?** A: It means the server didn't send the header that lets a local client, such as a browser, access its data. This is most common when trying to fetch data (usually JSON) that you want to process using JavaScript. **Q: What package does the article use to add CORS support?** A: Tuupola's Cors Middleware package, installed by running `composer require tuupola/cors-middleware` in the project. **Q: Where does the CORS configuration live?** A: In a `cors.global.php` file created in the config/autoload directory, containing a "cors" key with settings like origin, methods, headers.allow, headers.expose, credentials, and cache. **Q: How is the CorsMiddleware wired into the container?** A: A CorsMiddlewareFactory extracts the "cors" config array (or an empty array if it's not provided) and instantiates Tuupola's CorsMiddleware with it. That factory is registered under the "dependencies" > "factories" section of cors.global.php. **Q: Where should the CORS middleware be added in the pipeline?** A: In config/pipelines.php via `$app->pipe(CorsMiddleware::class)`, placed after the Error handler and before the middleware that provides the data you want to access. ## 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 a second caching layer to WURFL in Dotkernel using APC" description: "How adding a small, custom APC-based caching layer on top of WURFL's own cache cut response time by an order of magnitude." author: "Adrian" date_published: "2011-10-14" canonical_url: "https://www.dotkernel.com/dotkernel/adding-a-second-caching-layer-to-wurfl-in-dotkernel-using-apc/" category: "Dotkernel" language: "en" --- # Adding a second caching layer to WURFL in Dotkernel using APC ## TL;DR On a high-traffic project using WURFL, profiling showed WURFL's default filesystem cache was costing up to a few hundred milliseconds per request. Adding a small, custom second cache layer on top of WURFL, built on APC, cut response time by an order of magnitude, down to 20-30ms. ## The problem On one recent project that used WURFL, response time was an important factor. Profiling revealed that the greatest chunk of response time (up to a few hundred milliseconds) was taken up by WURFL. The default filesystem cache turned out to be too slow for a relatively high-traffic application. ## How WURFL's caching works 1. The device data is stored at first in a large, zipped XML file, with one entry for each device. 2. When first called, WURFL unzips the file and reads each device entry. 3. It then serializes the data and writes it to the cache, using an MD5 signature for the file name (or key name if the cache is not on the filesystem). 4. When a user agent is looked up, its MD5 signature is computed and then searched in the cache. 5. Because the data is stored as a tree, with each device inheriting the properties of the nodes above it, **each look-up requires a number of files to be read and their capabilities merged** to get all the capabilities of the requested device. WURFL also has cache providers for APC and memcache, which were tried, but the results weren't impressive. ## The solution The team realized their approach was wrong for their use case - the WURFL entry for a device has lots of fields that weren't actually used. The solution was adding a **second cache layer** on top of WURFL's own cache, which only cached the fields that were actually needed. This second layer used **APC**, storing arrays of data in **User Cache Entries**. This small change (under 10 lines of code) decreased response time by an **order of magnitude**, down to 20-30ms. ## FAQ **Q: Why was WURFL's default caching too slow for this project?** A: Profiling revealed that WURFL's default filesystem cache was taking up to a few hundred milliseconds of response time, which was too slow for a relatively high-traffic application. **Q: How does WURFL's caching work by default?** A: Device data is stored in a large zipped XML file. On first use, WURFL unzips the file, serializes each device's data, and writes it to cache using an MD5 signature of the user agent as the key. Because devices are stored as a tree inheriting properties from parent nodes, each lookup requires reading and merging several files. **Q: Did WURFL's built-in APC or memcache cache providers solve the problem?** A: No. The team tried WURFL's existing cache providers for APC and memcache, but the results weren't impressive. **Q: What was the actual solution?** A: Adding a second cache layer on top of WURFL's own cache, using APC and storing arrays of only the specific fields they actually needed in User Cache Entries. The change was under 10 lines of code. **Q: What performance improvement did this bring?** A: Response time decreased by an order of magnitude, down to about 20-30ms. --- 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**. ## FAQ **Q: What does Composer do?** A: Composer is an application-level package manager. It auto-loads dependencies on demand and can also auto-load custom classes. **Q: What must a Dotkernel project have before Composer can be used?** A: A composer.json file, for example requiring zendframework/zendframework1 at 1.12.* and mobiledetect/mobiledetectlib at 2.8.*, plus PHP >=5.4.0 listed under require-dev. **Q: What happens when you run composer update?** A: If the vendor folder already exists, Composer checks for and applies updates to the packages. If it doesn't exist, Composer creates the vendor folder containing all requested packages, along with an autoload file. **Q: How do you safely load the Composer autoloader in case Composer isn't present?** A: Check whether vendor/autoload.php exists using file_exists() before calling require_once() on it, and handle the case gracefully (for example by loading fallbacks) if the path is missing. **Q: Which Dotkernel versions does this apply to?** A: The article states it works for any Dotkernel 1.x version, as long as the server is running PHP greater than 5.4.0. ## Resources - [Composer install / PHP dependency manager tutorial](https://www.codementor.io/php/tutorial/composer-install-php-dependency-manager) --- title: "Adding Windows 10 OS and Browser detection in Dotkernel projects" description: "A guide to installing the patch that adds Windows 8, 8.1 and 10 OS icons and the Microsoft Edge browser icon in Dotkernel." author: "Gabi DJ" date_published: "2015-09-08" canonical_url: "https://www.dotkernel.com/dotkernel/adding-windows-10-os-and-browser-detection-in-dotkernel-projects/" category: "Dotkernel" language: "en" --- # Adding Windows 10 OS and Browser detection in Dotkernel projects ## TL;DR Dotkernel added Windows 8, 8.1 and 10 OS icons and a Microsoft Edge browser icon, shown in the User and Admin login icons. This article is the upgrade guide for applying that icon patch. ## Upgrade steps 1. Make sure your project is running version **1.5.0** or **newer**. 2. Download the [patch](http://www.dotkernel.com/download/?did=46). 3. Extract the archive into a folder, e.g. `icons_patch`. 4. Create a backup of your project before continuing (recommended). 5. Copy all the files in the `icons_patch` folder into your Dotkernel project. 6. You will be prompted to replace 2 files - replace them and agree to merge the folders' content (other files will be added, not replaced). 7. Clear the cache for changes to take effect, since the OS and browser XMLs are cached (see "Dotkernel Reserved Variable Names for Caching", the "Browser & OS" section). 8. You can now delete the `icons_patch` folder, or keep it to patch another project. ## Affected files ``` M /configs/useragent/browser.xml M /configs/useragent/os.xml A /images/browsers/edge.png A /images/os/windows_metro.png ``` `M` stands for **modify**, `A` stands for **add**. ## FAQ **Q: What Dotkernel version is required before applying this patch?** A: Your project must be running version 1.5.0 or newer. **Q: Which files does the patch modify or add?** A: It modifies configs/useragent/browser.xml and configs/useragent/os.xml, and adds images/browsers/edge.png and images/os/windows_metro.png. **Q: Why do you need to clear the cache after applying the patch?** A: Because the OS and browser XML files are cached, so the new icons won't show up until the cache is cleared. **Q: Will applying the patch overwrite existing files?** A: You'll be prompted to replace 2 files (browser.xml and os.xml) and should agree, and also agree to merge the folders' contents since the other files listed are added rather than replaced. ## Resources - [Icon patch download](http://www.dotkernel.com/download/?did=46) - [Dotkernel Reserved Variable Names for Caching](http://www.dotkernel.com/dotkernel/dotkernel-reserved-variable-names-for-caching) --- 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-using-cookie-remember-me-in-dotkernel/" 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). ## FAQ **Q: Since which release is Remember Me implemented in Dotkernel?** A: It's implemented in Dotkernel Frontend starting from Release 3.3.0. **Q: How do you add the Remember Me checkbox to the login UI?** A: In src/User/templates/user/login.html.twig, under the password element, render the rememberMe element retrieved via form.get('rememberMe') with formElement(). **Q: What form and validation changes are needed?** A: A 'rememberMe' checkbox element must be added to src/User/src/Form/LoginForm.php, and a StringTrim filter plus a NotEmpty validator must be added for it in src/User/src/InputFilter/LoginInputFilter.php. **Q: What backend pieces implement the actual remember-me functionality?** A: A new UserRememberMe entity, a database migration (created and run with phinx) for its table, a new RememberMeMiddleware registered in config/pipeline.php, a rememberMe cookie configuration block added to config/autoload/local.php, and new methods added to UserService, UserRepository, and UserController (including loginAction() and logoutAction()). **Q: What does the UserRememberMe table store?** A: It's used to store data from the cookie, which helps log the user in automatically. **Q: How do you apply the new remember-me button styles?** A: Add the CSS to src/App/assets/scss/components/_profile.scss, then run npm run prod to compile the CSS so the button styling takes effect. ## 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. ## FAQ **Q: What problem does this fix address?** A: When missing static files (images, CSS, JS) are routed through the bootstrap (index.php) and the session is set to regenerate on each request, the currently logged-in user gets logged off because the session ID changes. **Q: What is the fix?** A: Below the "RewriteEngine On" line, add a RewriteCond matching file extensions like .gif, .jpg, .png, .css, and .js, so requests for those files are not routed through the bootstrap. --- title: "Caching in Dotkernel using Zend Framework" description: "How Dotkernel's upcoming 1.8 cache layer stores router, ACL, menu and other data between requests, using APC/APCU or file storage." author: "Gabi DJ" date_published: "2015-01-29" canonical_url: "https://www.dotkernel.com/dotkernel/caching-in-dotkernel-using-zend-framework/" category: "Dotkernel" language: "en" --- # Caching in Dotkernel using Zend Framework ## TL;DR Loading configuration and settings from XML files on every request is expensive, both due to hard-drive latency and XML parsing overhead. Dotkernel 1.8 implements a cache layer for router, acl_role, menu, options (including seo_xml), browser_xml, os_xml and test data, with a choice of APC/APCU or file-based storage. ## 1. Configuring the cache The configuration is set from `/configs/application.ini`: whether caching is enabled, how long the cache stays valid, the cache namespace, and the storage provider (File or APC). The article recommends disabling the cache in development mode. See [Configuring the Cache in Dotkernel](http://www.dotkernel.com/dotkernel/configuring-the-cache-in-dotkernel/) for more details. ## 2. Using the cache The cache is automatically loaded during initialization and stored in the Registry - loading it manually is not needed because it's already loaded on kernel initialization (see `Dot_Kernel::initialize($startTime)`). If you want to use caching outside of that normal initialization, load it with: ```php Dot_Cache::loadCache(); ``` Note: the cache key must match a specific RegEx pattern. Example of object caching: ```php $id = 'MyCachedKey'; $obj = new stdClass(); $obj->text = 'I am a cached text'; // saving an object Dot_Cache::save(obj, $id); // loading the object $value = Dot_Cache::load($id); // checking if we have the object in cache if ($value !== false) { // assuming we only need the text value from the object echo $value->text; } else { echo 'no value cached for '. $id ; } ``` ## FAQ **Q: What data does Dotkernel's cache layer store?** A: Router, acl_role, menu, options (including seo_xml), browser_xml, os_xml, and test data between requests. **Q: What storage providers are available for the cache?** A: Two cache factories to choose from: APC (or APCU for newer PHP installations) and File. **Q: Where is the cache configured?** A: In /configs/application.ini, where you can enable or disable caching, set how long the cache stays valid, choose the cache namespace, and pick the storage provider (File or APC). The article recommends disabling the cache in development mode. **Q: Do you need to manually load the cache engine?** A: No, it's automatically loaded during kernel initialization (Dot_Kernel::initialize()). Manually calling Dot_Cache::loadCache() is only needed if you want to use caching outside of that normal initialization. **Q: Can you cache PHP objects, not just simple values?** A: Yes, the article shows an example of saving and loading a stdClass object using Dot_Cache::save() and Dot_Cache::load(). ## Resources - [Dotkernel Reserved Variable Names for Caching](http://www.dotkernel.com/dotkernel/dotkernel-reserved-variable-names-for-caching) - [Configuring the Cache in Dotkernel](http://www.dotkernel.com/dotkernel/configuring-the-cache-in-dotkernel/) --- title: "camelCase Table Names in MySQL on Windows" description: "How to fix MySQL on WAMP/XAMPP lowercasing camelCase table names by setting lower_case_table_names=2 in my.cnf." author: "admin" date_published: "2010-03-12" canonical_url: "https://www.dotkernel.com/dotkernel/camelcase-table-names-in-mysql-on-windows/" category: "Dotkernel" language: "en" --- # camelCase Table Names in MySQL on Windows If you are using a WAMP stack, like WAMP or XAMPP, and try to create a table in camelCase (example: `adminLogin`), you will notice that camelCase is not working - the table name will be lowercase: `adminlogin`. In order to fix this, add the following line to your `my.cnf` file: ``` lower_case_table_names=2 ``` and restart MySQL. ## FAQ **Q: What happens when you create a camelCase table name on WAMP or XAMPP?** A: A table created with a camelCase name, for example adminLogin, ends up stored as all lowercase, e.g. adminlogin, instead. **Q: How do you fix it?** A: Add the line `lower_case_table_names=2` to your my.cnf file and restart MySQL. ## Resources - [MySQL lower_case_table_names documentation](http://dev.mysql.com/doc/refman/4.1/en/server-system-variables.html#sysvar_lower_case_table_names) --- 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](http://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=). ## FAQ **Q: How many Zend Certified Engineers does the team have?** A: According to the article, 2 more team members passed the ZCE exam, bringing the team's total to 5 Zend Certified Engineers. ## Resources - [Zend Yellow Pages listing](http://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: "Configuring the Cache in Dotkernel" description: "A configuration guide for Dotkernel's Zend Framework Cache-based caching layer, covering the main frontend settings and the optional per-backend settings." author: "Gabi DJ" date_published: "2015-01-29" canonical_url: "https://www.dotkernel.com/dotkernel/configuring-the-cache-in-dotkernel/" category: "Dotkernel" language: "en" --- # Configuring the Cache in Dotkernel ## TL;DR Dotkernel's caching layer is built on Zend Framework Cache and is configured through `cache.*` settings in `application.ini`. The main frontend settings control whether caching is enabled, which cache service to use, the namespace prefix, and how long entries live. Optional backend-specific settings (like the file cache directory) are recommended so that separate projects don't accidentally share the same cache. This article contains the Dotkernel cache layer configuration guide. The Dotkernel Caching Layer is based on Zend Framework Cache; more configuration options can be found at the following links: - [Zend Framework Cache Frontends](http://framework.zend.com/manual/1.12/en/zend.cache.frontends.html) - [Zend Framework Cache Backends](http://framework.zend.com/manual/1.12/en/zend.cache.backends.html) ## Main Cache Settings (Cache Frontend) The main cache settings within the application.ini file should look like this: ```ini cache.enable = true cache.factory = "apc" cache.lifetime = "86400" cache.namespace = "dotkernel" ``` The cache.enable option can be used to disable caching, mostly used in the development stage. The cache.factory value will be the cache service we want to use: file or apc. The cache.namespace will be the cache variables prefix, and the cache.lifetime value will define how long the cached variables will be usable before they need to be re-cached. ## Individual Cache Settings (Cache Backend) The individual cache settings are optional, but it's highly recommended that you have these values set, otherwise other projects might use the same cache. ```ini ; file caching settings cache.file.cache_dir = APPLICATION_PATH "/cache" cache.file.cache_file_perm = 0600 ``` For more settings and caching alternatives, see the Zend Framework Cache links at the beginning of the article. The setting pattern and sample are below: ```ini cache.BACKEND_NAME.SETTING = "VALUE" ; example: cache.file.file_name_prefix = "Dotkernel" ``` ## FAQ **Q: What is Dotkernel's caching layer based on?** A: It's based on Zend Framework Cache, configured through settings in application.ini, with more configuration options available at the Zend Framework Cache Frontends and Backends documentation links given in the article. **Q: What does the cache.enable setting do?** A: It can be used to disable caching, which is mostly useful during the development stage. **Q: What values can cache.factory take?** A: The cache.factory value is the cache service to use, and the article lists two options: file or apc. **Q: Why bother setting the individual/backend cache settings like cache.file.cache_dir?** A: These settings are optional, but the article highly recommends setting them, otherwise other projects might end up using the same cache. --- 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/). ## FAQ **Q: What problem does dot-dependency-injection solve?** A: In Laminas/Mezzio applications, developers normally have to build, update, and maintain a factory class for every class that needs dependencies. dot-dependency-injection autowires those dependencies instead, so you don't need a factory for every class. **Q: Does dot-dependency-injection require Doctrine ORM?** A: The package requires Doctrine ORM, but the article notes it can still be used in applications that don't integrate Doctrine. **Q: How do you mark a class's constructor dependencies for injection?** A: Import Dot\DependencyInjection\Attribute\Inject in the class, then add the attribute to the constructor definition to specify which dependencies should be injected. **Q: What do you need to add to the ConfigProvider to use this package?** A: Only the Dot\DependencyInjection\Factory\AttributedServiceFactory class needs to be added to your config's dependencies. It builds the factory for you and handles the logic for dependencies missing from the container, with appropriate exceptions and messages. **Q: Can this package be used with the Doctrine repository pattern?** A: Yes. If you don't want to fetch a repository from the EntityManager and instead want to inject it directly into your service, the article says this package covers that too, following the same principle, with more details in the package documentation. --- title: "Detecting Mobile Devices in Dotkernel 1.6.0" description: "Explains how mobile device detection changed in Dotkernel 1.6.0 with the move to Wurfl Cloud, including the required application.ini settings and sample Dot_UserAgent usage code." author: "deddu" date_published: "2012-05-18" canonical_url: "https://www.dotkernel.com/dotkernel/detecting-mobile-devices-in-dotkernel-1-6-0/" category: "Dotkernel" language: "en" --- # Detecting Mobile Devices in Dotkernel 1.6.0 ## TL;DR Dotkernel 1.6.0 no longer ships with a working built-in mobile detection method, because mobile detection now relies on the new Wurfl Cloud integration and must be configured via a Wurfl Cloud account and API key. The old Dot_UserAgent_Wurfl class was removed and replaced by Dot_UserAgent_WurflCloud, which uses the Wurfl Cloud API adapter. The article walks through the application.ini settings and shows sample code for reading device info and redirecting mobile visitors. The new Dotkernel version 1.6.0 is coming with some changes to how we detect mobile devices; these changes are because of the new Wurfl Cloud integration. This version of Dotkernel no longer comes with a working built-in method for mobile detection, so first we have to configure it. - Go to the scientiamobile website and register for a Wurfl Cloud account. - Choose device_os and mobile_browser for your account and save. - Go to API Keys and copy the right key into application.ini. We chose device_os and mobile_browser capabilities because with these two capabilities we can get some extra capabilities (isMobile, isSmartPhone, isIphone, isAndroid, isBlackberry, isSymbian, and isWindowsMobile) using our built-in methods. Choosing other capabilities from scientiamobile will result in wrong detection of these extra capabilities, but you can get only those capabilities using another method from the Dot_UserAgent_WurflCloud class. Wurfl Cloud setting in application.ini: ```ini resources.useragent.wurflcloud.active = TRUE resources.useragent.wurflcloud.redirect = TRUE resources.useragent.wurflcloud.cache = TRUE resources.useragent.wurflcloud.cache_lifetime = 3600 resources.useragent.wurflcloud.cache_namespace = WURFLCLOUD resources.useragent.wurflcloud.api_key = 000000:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX resources.useragent.wurflcloud.lib_dir = APPLICATION_PATH "/library/WurflCloud/" ``` - active - used to turn on (TRUE) or off (FALSE) the Wurfl Cloud detection (default: TRUE). - redirect - if TRUE, visitors from the frontend will be redirected to the mobile module (default: TRUE). - cache - caches every distinct result to optimize the number of requests to scientiamobile (default: TRUE). - cache_lifetime - time in seconds to keep the results in cache (default: 3600). - cache_namespace - the prefix used for cache keys (default: WURFLCLOUD). - api_key - the API key from your WURFL Cloud account (change this to your own key). - lib_dir - the Wurfl Cloud library location in Dotkernel (don't change this, unless you want to move the library). Because of these changes, we removed the old Dot_UserAgent_Wurfl class and added the new Dot_UserAgent_WurflCloud class, which uses the Wurfl Cloud API adapter. ## Example of Dot_UserAgent Usage in Dotkernel Get Wurfl configuration: ```php $wurflConf = $registry->configuration->resources->useragent->wurflcloud; ``` Note: you can have more Wurfl configurations if you have more libraries, like the Wurfl Package (GPL). If Wurfl is active, then get device info: ```php if($wurflConf->active) { $deviceInfo = Dot_UserAgent :: getDeviceInfo($_SERVER); ... } ``` If the detected device is a mobile device, we save the device info in the database and redirect it to the mobile controller: ```php if( (0 < count((array)$deviceInfo)) && $deviceInfo->isMobile) { if(!$registry->session->visitId) { $registry->session->visitId = Dot_Statistic::registerVisit(); } // if the Statistic module is integrate, record the deviceInfo too, and record TRUE //in $session->mobile if(!$registry->session->mobile) { $registry->session->mobile = Dot_Statistic::registerMobileDetails($registry->session->visitId, $deviceInfo); //redirect to mobile controller , only if the session is not set. //Otherwise will trap the user in mobile controller if($wurflConf->redirect) { header('location: '. $registry->configuration->website->params->url.'/mobile'); exit; } } } ``` ## FAQ **Q: Why did mobile detection change in Dotkernel 1.6.0?** A: Because of the new Wurfl Cloud integration. This version no longer ships with a working built-in method for mobile detection, so it must be configured first. **Q: What are the steps to configure Wurfl Cloud detection?** A: Go to the scientiamobile website and register for a Wurfl Cloud account, choose the device_os and mobile_browser capabilities for the account and save, then go to API Keys and copy the key into application.ini. **Q: Why choose the device_os and mobile_browser capabilities specifically?** A: With these two capabilities, Dotkernel's built-in methods can also derive extra capabilities such as isMobile, isSmartPhone, isIphone, isAndroid, isBlackberry, isSymbian, and isWindowsMobile. Choosing other capabilities from scientiamobile results in wrong detection of these extra capabilities. **Q: What happened to the old Dot_UserAgent_Wurfl class?** A: It was removed and replaced with the new Dot_UserAgent_WurflCloud class, which uses the Wurfl Cloud API adapter. **Q: What does the redirect setting in application.ini control?** A: When resources.useragent.wurflcloud.redirect is TRUE (the default), visitors from the frontend are redirected to the mobile module the first time a mobile device is detected. --- title: "Disable Wurfl redirect for mobile browsers" description: "Shows the application.ini setting introduced in revision 408 to control Dotkernel's automatic Wurfl-based redirect of mobile visitors to the mobile site, and the code that checks it." author: "Adrian" date_published: "2011-01-31" canonical_url: "https://www.dotkernel.com/dotkernel/disable-wurfl-redirect-for-mobile-browsers/" category: "Dotkernel" language: "en" --- # Disable Wurfl redirect for mobile browsers ## TL;DR Dotkernel's example mobile site normally relies on Wurfl to detect mobile browsers and automatically redirect visitors there on their first homepage view, which isn't always desired. As of revision 408, this behavior is controlled by a single `resources.useragent.wurflapi.redirect` setting in application.ini. The article shows that setting along with the matching condition in `IndexController.php` that checks it before registering and redirecting a visit. Dotkernel has an example mobile site at [http://v1.dotkernel.net/mobile](http://v1.dotkernel.net/mobile) that uses [jQuery Mobile](http://jquerymobile.com/). Wurfl is also used to detect mobile browsers (as discussed in a [previous blog post](http://www.dotkernel.com/dotkernel/wurfl-zend-framework-integration-into-dotkernel/)) and automatically redirect them to the mobile site the first time they view the homepage. Sometimes this behavior isn't desired (for example when you don't have a mobile site, or you don't plan on using Wurfl at all). Starting with revision 408, there's an option in application.ini to disable the automatic redirect (by default the redirect is disabled): ```ini resources.useragent.wurflapi.redirect = false ``` The following condition is also added to Controllers/frontend/IndexController.php (at line 19) to check the configuration: ```php //if automatic redirect is enabled in application.ini and the browser is mobile and session->mobileHit is not set, register it and redirect if($config->resources->useragent->wurflapi->redirect && 'mobile' == Dot_Kernel::getDevice()->getType() && !isset($session->mobileHit)) ``` ## FAQ **Q: How do you disable the automatic mobile redirect in Dotkernel?** A: Starting with revision 408, set resources.useragent.wurflapi.redirect = false in application.ini. Per the article, this is also the default state of the redirect option. **Q: Where in the code is this configuration option checked?** A: In Controllers/frontend/IndexController.php (around line 19), a condition checks whether the redirect is enabled in application.ini, whether the visiting browser is mobile, and whether session->mobileHit isn't already set, before registering and redirecting the visit. --- 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 Dotkernel? The name Dotkernel symbiotically combines the string Dot, as a representation of the Internet, and Kernel, the quintessence of any IT application. In other words, Dotkernel wishes to be, with modesty, the central part of Internet development, ensuring increased development productivity and run-time performance. ## What Is Dotkernel 1? Dotkernel 1 is a PHP Application Framework, built on top of Zend Framework 1 (ZF1). It had its first public release in July 2010. It is tightly coupled with Zend Framework 1, and adds a set of custom or external features (such as Router, Template Engine, etc.). It is composed of Zend Framework 1 and a set of custom or external features (such as Router, Template Engine, etc.). Dotkernel 1's architecture is based on MVC. The latest version is 1.8 Long Term Support. No new version will be released anymore, only bugfixes. ## What Is Dotkernel 3? A collection of PSR-7 Middleware applications built on top of the [Zend Expressive](https://docs.zendframework.com/zend-expressive/) microframework. It is composed of a set of custom and extended [Zend Framework 3](https://framework.zend.com/) components. Dotkernel 3's architecture is based on Middleware. Dotkernel implements the following PSRs: PSR-1, PSR-2, PSR-4, PSR-7, PSR-11. Currently there are 2 applications: Frontend and Admin, and a 3rd one is under development: API. ## Dotkernel = Dotkernel 1 or Dotkernel 3? In posts older than 2017, Dotkernel 1 was referred to as Dotkernel, because it was the only Dotkernel version. Since the release of Dotkernel 3, it is referred to as Dotkernel 3 or Dotkernel. All future references to Dotkernel 1 will be explicitly made. ### As of Dotkernel 3 Release: Dotkernel 1 = Dotkernel 1 Dotkernel 3 = Dotkernel 3 #### Dotkernel = Dotkernel 3 ## FAQ **Q: What does the name "Dotkernel" mean?** A: It combines "Dot", as a representation of the Internet, with "Kernel", the quintessence of any IT application, reflecting the aim of being a central part of Internet development. **Q: What is Dotkernel 1?** A: A PHP Application Framework built on top of Zend Framework 1, first publicly released in July 2010, with an architecture based on MVC. Its latest version is 1.8 Long Term Support, which per the article will not be followed by a new version, only bugfixes. **Q: What is Dotkernel 3?** A: A collection of PSR-7 Middleware applications built on top of the Zend Expressive microframework, composed of a set of custom and extended Zend Framework 3 components, with an architecture based on Middleware. It implements PSR-1, PSR-2, PSR-4, PSR-7, and PSR-11. **Q: How many applications make up Dotkernel 3?** A: At the time of the article, there were two available applications, Frontend and Admin, with a third one, API, under development. **Q: When someone writes just "Dotkernel", which version is meant?** A: In posts older than 2017, "Dotkernel" referred to Dotkernel 1, since it was the only version. Since the release of Dotkernel 3, "Dotkernel" refers to Dotkernel 3, and all future references to Dotkernel 1 are made explicitly. --- 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. ## 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. ## FAQ **Q: What component does this article use for caching Doctrine data?** A: The dotkernel/dot-cache component, a wrapper that sits on top of symfony/cache. It's installed with composer require dotkernel/dot-cache and registered by adding DotCacheConfigProvider::class to the configuration aggregate. **Q: What storage adapters does dot-cache currently support?** A: Two: array, which stores data in-memory and is the fastest option but uses more RAM, and filesystem, which stores data in local disk files and is slightly slower but more persistent. **Q: What are the four types of Doctrine cache covered?** A: result_cache, metadata_cache, query_cache, and hydration_cache, each configured under the doctrine.configuration.orm_default key. **Q: What does the result cache do?** A: It stores the results of queries, letting Doctrine avoid querying the database or hydrating the data again after the initial retrieval. **Q: Why cache class metadata?** A: Because parsing class metadata on every request is inefficient, so it's advisable to cache it using one of the available cache adapters. **Q: How do you mark an entity or a query as cacheable?** A: To enable caching for entities you add a caching attribute to the entity class; to cache an individual query, call setCacheable(true) on the query builder before getResult(). --- 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 # class Card { # # # public int $id; #], )] public Suit $suit; } ``` ### New Setup ```php # class Card { # # # public int $id; # 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 = ; ``` The column for the ORM was defined like this, as a simple string, with `pending` as its default value: ```php # 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, , 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 #)] 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 !== 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) ->usePassword($data) ->setStatus($data ?? UserStatusEnum::Pending); ``` Note the `status` column in the migration query which now looks like this: ```php $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. ## FAQ **Q: What update triggered this change to Dotkernel's enum handling?** A: The update of doctrine/orm to version 3.2.0 introduced EnumType columns, building on the enum type introduced in PHP 8.1. Dotkernel implemented this new data type on both the PHP side and the database side. **Q: What was the limitation of Dotkernel's old approach to columns like User->Status?** A: The old setup used a simple string type, so the value set couldn't be definitively enforced. A typo in a PHP value would still be accepted, and the database was independent of any values the PHP code allowed, so manually editing a value in the database would accept any string. **Q: What was the one advantage of the old string-based setup?** A: It made it easy to add more values to the value set, though the article notes this ease also invites bugs in the execution. **Q: What do you need to create to add a new custom enum type?** A: A PHP enum class (like UserStatusEnum) plus a DBAL type class extending AbstractEnumType, which must define a NAME constant and a getEnumClass() method; the new type is then registered under the types key in config/autoload/doctrine.global.php. **Q: Does Types::ENUM still fall back to a string or integer database column?** A: The article notes that Doctrine still defaults to Types::STRING or Types::INTEGER for columns backed by a PHP enum, as this is considered the more portable and safer default; Types::ENUM is required if you want an actual enum column in MySQL/MariaDB. **Q: What must happen when the value set of an enum changes under the new setup?** A: Any update to the value set must be made on both the PHP code and the database, since the new setup creates an explicit, enforced link between them. ## 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: "DotBoost Technologies : Products and Services North American Relaunch" description: "Dotboost Technologies announces its North American relaunch, centered on the source release of its in-house Dotkernel framework alongside expanded IT integration and consulting services." author: "admin" date_published: "2010-01-28" canonical_url: "https://www.dotkernel.com/dotkernel/dotboost-technologies-products-and-services-north-american-relaunch/" category: "Dotkernel" language: "en" --- # DotBoost Technologies : Products and Services North American Relaunch ## TL;DR Dotboost announces its North American relaunch, aimed at better serving clients in Canada and the US. The relaunch centers on the source release of its in-house Dotkernel framework, along with expanded business IT integration and clearer consulting services. Founded in 2005, Dotboost describes itself as treating clients as strategic partners rather than as a typical IT vendor. ## The North American Relaunch A new style and advanced approach to accompany the Dotkernel source release. Dotboost is pleased to announce our North American Relaunch. This new phase comes as a result of dedicated research and analysis on how to best serve clients in Canada and the US. At the heart of our relaunch is the source release for our exclusive inhouse developed Dotkernel framework. We have also added business IT integration and increased the clarity to our existing consulting services. ## The Dotboost Approach We're not your average IT organization; we view our customers as strategic partners. This paradigm allows us to take a comprehensive approach towards creating solutions and gain the competitive advantage. Founded in 2005, the Dotboost process can incorporate anywhere into your project's life-cycle including concept development, architecture and design, development and integration, and implementation and support. We use time and distance to our advantage, pushing competitive boundaries and staking our place as a globally efficient organization. ## FAQ **Q: What is at the heart of Dotboost's North American relaunch?** A: The source release of Dotboost's exclusive, in-house developed Dotkernel framework, along with added business IT integration and increased clarity around existing consulting services. **Q: When was Dotboost founded, and at what stages can it join a project?** A: Dotboost was founded in 2005. Per the article, its process can incorporate anywhere into a project's life-cycle, including concept development, architecture and design, development and integration, and implementation and support. --- title: "Dotkernel 1.2.0 release" description: "Release notes for Dotkernel 1.2.0, covering database naming convention changes, the new 'dots' submodule concept, new and updated library classes, and the use of prepared statements for all SQL queries." author: "Teo" date_published: "2010-07-05" canonical_url: "https://www.dotkernel.com/dotkernel/dotkernel-1-2-0-release/" category: "Dotkernel" language: "en" --- # Dotkernel 1.2.0 release ## TL;DR Dotkernel 1.2.0 has been released, bringing changes since the previous 1.1.2 release. The database tables were renamed and restructured to follow database naming conventions, and configuration for each "dots" (submodule) now lives in XML files instead of being hard-coded in PHP. The release also adds new library classes (Dot_Geoip, Dot_Seo), updates existing ones (Dot_Curl, Dot_Session), and confirms that all SQL queries are written as prepared statements. ## Database Naming Conventions On database, we changed the names and structure of tables to respect database naming convention. See [http://www.dotkernel.com/dotkernel/dotkernel-database-naming-conventions-for-mysql/](http://www.dotkernel.com/dotkernel/dotkernel-database-naming-conventions-for-mysql/) for details. ## The "Dots" Concept A new word came into our Dotkernel discussions: dots. We use this term when talking about a submodule and all its component files. For example, "user" is a submodule of the frontend module. Note that one dots can be part of multiple modules (for example, "user" dots belong to both the frontend and admin module). For each dots, the configuration values have been added to XML files which are stored in the configs/dots folder. In the previous versions, these values were hard-coded in the PHP files. Another change made in the configs folder is resource.xml, which contains the configuration values for the controllers of each module. To be easier to start an application from Dotkernel, in the admin module, there are now the following dots: admin, user and system. ## Library Class Updates New library classes have been implemented: Dot_Geoip and Dot_Seo, and some of the existing ones have been updated: Dot_Curl and Dot_Session (each module has its own session). ## SQL Prepared Statements In Dotkernel, all SQL queries are written as prepared statements. We strongly encourage this practice: [http://www.dotkernel.com/php-development/protection-against-sql-injection-using-pdo-and-zend-framework/](http://www.dotkernel.com/php-development/protection-against-sql-injection-using-pdo-and-zend-framework/) For more details, see [ChangeLog 1.2.0](http://www.dotkernel.com/changelog/1-2-0/). ## FAQ **Q: What is a "dots" in Dotkernel, a term introduced in this release?** A: A term for a submodule and all its component files. For example, "user" is a dots of the frontend module, and one dots can belong to multiple modules, such as "user" belonging to both frontend and admin. **Q: Where are dots configuration values stored, compared to earlier versions?** A: They're stored in XML files inside the configs/dots folder. In previous versions, these values were hard-coded in the PHP files. **Q: What dots does the admin module include by default?** A: admin, user, and system, to make it easier to start an application from Dotkernel. **Q: What library classes were added or updated in 1.2.0?** A: Dot_Geoip and Dot_Seo were newly implemented, while Dot_Curl and Dot_Session were updated, with each module now having its own session. **Q: How are SQL queries written in Dotkernel?** A: All SQL queries are written as prepared statements, a practice the article strongly encourages. --- title: "Dotkernel 1.2.2 release" description: "Dotkernel 1.2.2 is a bug-fix release closing five issues, including captcha error handling, a pagination bug, and a copyright line update that touched every PHP file." author: "Teo" date_published: "2010-07-30" canonical_url: "https://www.dotkernel.com/dotkernel/dotkernel-1-2-2-release/" category: "Dotkernel" language: "en" --- # Dotkernel 1.2.2 release ## TL;DR Dotkernel 1.2.2 is a bug-fix release that closes five tracked issues. Because one of the fixes updated the copyright line, every PHP file in the codebase changed, so the full release or the incremental upgrade package is needed. ## Bug fixes in 1.2.2 - **31** - captcha errors try/catch - **32** - pagination issue - **33** - admin wrong link - **34** - Acunetix scan results from July 24th (notices and one fatal error) - **35** - update copyright line in files **Note:** because of bug 35, all PHP files changed in this release. ## Upgrading To get only the changed files from 1.2.1 to 1.2.2, download the upgrade package (linked in the post) instead of the full distribution. Full details are available in the ChangeLog 1.2.2, and further changes can be tracked on the Dotkernel Tracker or Dotkernel WebSVN. Note also that Dotkernel 1.2.1 had been released a few days earlier, on July 22, 2010, with its own ChangeLog and upgrade package. ## FAQ **Q: What does the Dotkernel 1.2.2 release include?** A: It's a bug-fix release that closes five issues: captcha error handling (try/catch), a pagination issue, a wrong admin link, notices and a fatal error found by an Acunetix scan, and an update to the copyright line in files. **Q: Why did all PHP files change in the 1.2.2 release?** A: Because of the fix for bug 35, which updated the copyright line, every PHP file in the codebase was touched, which is why the note in the post warns that all PHP files have changed. **Q: How can I upgrade from a previous version to 1.2.2?** A: You can download just the changed files from 1.2.1 to 1.2.2 using the upgrade package linked in the post, or check the ChangeLog 1.2.2 for full details of what changed. ## Resources - ChangeLog 1.2.2 (linked in the original post as `../changelog/1-2-2/`) - Upgrade package for 1.2.2 (linked in the original post as `../download/?did=17`) - Dotkernel Tracker: http://www.dotkernel.net/ - Dotkernel WebSVN: http://websvn.dotkernel.net/listing.php?repname=Dotkernel+ver.+1 - ChangeLog 1.2.1 (linked in the original post as `../changelog/1-2-1/`) - Upgrade package for 1.2.1 (linked in the original post as `../download/?did=14`) --- title: "Dotkernel 1.3.0 release" description: "Dotkernel 1.3.0 adds an admin skin switcher, a way to protect member-only links, and reorganizes resource.xml into route.xml and dots.xml, at the cost of backward compatibility." author: "Teo" date_published: "2010-10-15" canonical_url: "https://www.dotkernel.com/dotkernel/dotkernel-1-3-0-release/" category: "Dotkernel" language: "en" --- # Dotkernel 1.3.0 release ## TL;DR Dotkernel 1.3.0 brings a switchable admin skin, a way to protect member-only pages, a rename of Dot_Sessions, and a reorganization of resource.xml into route.xml and dots.xml. Because of that XML reorganization, 1.3.0 is not backward compatible with earlier versions. ## Highlights ### Admin skin switcher The admin skin can now be customized. Several ready-made skins are available: blue, brown, gray, and green. Set the skin by changing the `settings.admin.skin` value (e.g. `settings.admin.skin = green`). ### Protecting member-only links To protect a link so only logged-in members can access it, add this line in the controller file above the code that should require login: ```php Dot_Auth::checkIdentity(); ``` ### XML reorganization Some XML files from the configs folder were changed. `resource.xml` was deleted and its content was split between two new files, `route.xml` and `dots.xml`. ### Other closed issues The release also closed a number of other tracked issues, covering: the Dot_Sessions rename, menu issues in Admin and frontend, URL casing consistency, an XSS issue in the forgot-password flow, several security scan results, admin listing/UI fixes, a GeoIP extension listing feature, and formatting cleanup (blank lines, brace placement) across the frontend files. ## Compatibility note Because of the XML file reorganization, this release is **not compatible** with previous versions. Further details on what changed are available on the Dotkernel Tracker or Dotkernel WebSVN. ## FAQ **Q: What is new in the admin interface in Dotkernel 1.3.0?** A: 1.3.0 adds a skin switcher for the admin, with several ready-made skins (blue, brown, gray, green) that can be set via the settings.admin.skin configuration value. **Q: How do I protect a page so only logged-in members can access it?** A: Add the line Dot_Auth::checkIdentity(); in the controller file above the code you want to protect - everything below that line requires the visitor to be logged in. **Q: What happened to resource.xml in this release?** A: resource.xml was deleted and its content split between two new files, route.xml and dots.xml. **Q: Is Dotkernel 1.3.0 backward compatible with earlier versions?** A: No. Because of the XML file reorganization (bug 69), 1.3.0 is not compatible with previous versions. ## Resources - Dotkernel 1.3.0 download (linked in the original post as `../download/?did=23`) - ChangeLog 1.3.0 (linked in the original post as `../changelog/1-3-0/`) - route.xml documentation (linked in the original post as `../docs/router-xml/`) - dots.xml documentation (linked in the original post as `../docs/dots-xml/`) - Dotkernel Tracker: http://www.dotkernel.net/ - Dotkernel WebSVN: http://websvn.dotkernel.net/listing.php?repname=Dotkernel --- title: "Dotkernel 1.3.2 release" description: "Dotkernel 1.3.2 is a maintenance release with many bug fixes, a couple of minor features, and some refactoring, released just before the winter holidays." author: "Teo" date_published: "2010-12-23" canonical_url: "https://www.dotkernel.com/dotkernel/dotkernel-1-3-2-release/" category: "Dotkernel" language: "en" --- # Dotkernel 1.3.2 release ## TL;DR Released just before the winter holidays, Dotkernel 1.3.2 is mainly a maintenance release: it contains many bug fixes, some refactoring, and a few minor features. ## Bug fixes - CSS issue on the admin phpinfo page - Warning in the admin dashboard for a file - WURFL cache issue in admin - WURFL version issue - Dot_Paginator bug - Zend Paginator double-query issue - Database naming convention issue - Database normalisation/refactor ## Minor features - Refactor of validIP in the Dot_Kernel class - WURFL date and API version shown in admin ## Refactoring - Zend_Paginator refactoring - Added a dojo dijit theme to Dotkernel ## FAQ **Q: What kind of release is Dotkernel 1.3.2?** A: It's mainly a maintenance release, containing many bug fixes, some refactoring, and a few minor features. **Q: What bugs were fixed in 1.3.2?** A: Fixes include a CSS issue on the admin phpinfo page, a warning in the admin dashboard, a WURFL cache issue and WURFL version issue in admin, a Dot_Paginator bug, a Zend Paginator double-query issue, and a database naming convention issue. **Q: What minor features and refactoring were included?** A: Minor features include a refactor of validIP in Dot_Kernel and showing the WURFL date and API version in admin. Refactoring covered Zend_Paginator and added a dojo dijit theme to Dotkernel. ## Resources - Dotkernel 1.3.2 download: http://www.dotkernel.com/download/?did=27 --- title: "Dotkernel 1.5.0 Released" description: "Dotkernel 1.5.0 skips version 1.4 entirely and brings a switch from Dojo to jQuery, redesigned admin and frontend, model inheritance via Dot_Model, dashed controller support, and a reorganized Zend Registry." author: "Adrian" date_published: "2011-06-15" canonical_url: "https://www.dotkernel.com/dotkernel/dotkernel-1-5-0-released/" category: "Dotkernel" language: "en" --- # Dotkernel 1.5.0 Released ## TL;DR After a longer wait than usual and around 250 commits, Dotkernel 1.5.0 was released, skipping 1.4 entirely due to the scale of changes. Highlights include switching from Dojo to jQuery, a redesigned admin and frontend, model inheritance through a new Dot_Model class, support for dashed controller names, and a reorganized Zend Registry. ## Why skip straight to 1.5.0? Due to the large amount of changes and the long time spent in development, the team chose to skip 1.4 and go straight to 1.5.0. ## Highlights of 1.5.0 ### Switched from Dojo to jQuery Starting with 1.5.0, Dotkernel switched from using Dojo to jQuery. Dojo can still be used in your own projects, but only jQuery is used and maintained in the Dotkernel distribution itself. ### New designs The admin site was redesigned, with new themes and a dropdown menu, along with a new and simpler design for the front-end. ### Model inheritance Previously there was a lot of code duplication in models - for example, a `getUserById` function might exist separately in both the admin and frontend User models. To solve this, a `Dot_Model` class was introduced along with a way to define global models inherited by both admin and frontend. A `User` class in the admin only holds admin-specific methods, a `User` class in the frontend only holds frontend-specific methods, and both inherit a shared `Dot_Model_User` class containing the common code. ### Dashed controllers The way controller names are parsed was changed so that controllers with multiple words, split with dashes, work without breaking the coding standard. For example, `www.example.com/search-article` calls `SearchArticleController.php`. ### Zend Registry reorganization The structure of the registry was changed; more details are covered in a separate blog post on Zend Registry usage in Dotkernel. ## Scale of the release There were about 250 commits in the SVN repository since the previous release, so the blog post could not cover every change. ## FAQ **Q: Why did Dotkernel jump from 1.3 straight to 1.5.0?** A: Because of the large amount of changes and the long time spent in development, the team chose to skip version 1.4 and go straight to 1.5.0. **Q: Did Dotkernel switch from Dojo to jQuery in 1.5.0?** A: Yes. Starting with 1.5.0, Dotkernel switched from Dojo to jQuery for its own distribution, though Dojo can still be used in your own projects. **Q: What is Dot_Model and why was it introduced?** A: Dot_Model is a base class introduced to reduce code duplication between admin and frontend models. Both admin- and frontend-specific model classes (such as User) inherit from a shared Dot_Model_User class that holds the common code. **Q: How does the "dashed controllers" feature work?** A: The controller name parsing was changed so a URL like www.example.com/search-article correctly calls SearchArticleController.php, allowing multi-word controller names split with dashes without breaking the coding standard. **Q: How much changed in the 1.5.0 release?** A: About 250 commits went into the SVN repository since the previous release, so the blog post only covers the highlights - the full Dotkernel 1.5.0 download is available to try out. ## Resources - Intro to jQuery: http://www.dotkernel.com/javascript/intro-to-jquery/ - Zend Registry usage in Dotkernel: http://www.dotkernel.com/dotkernel/zend-registry-usage-in-dotkernel/ - Dotkernel 1.5.0 download: http://www.dotkernel.com/download/?did=33 --- title: "Dotkernel 1.8.0 LTS Released" description: "Dotkernel 1.8.0 (LTS) introduces a plugin architecture, a redesigned mobile-friendly admin and frontend, APC/File caching for speed, a new Dot_Request class, and several security and alerting improvements." author: "Gabi DJ" date_published: "2015-06-08" canonical_url: "https://www.dotkernel.com/dotkernel/dotkernel-1-8-0-lts-released/" category: "Dotkernel" language: "en" --- # Dotkernel 1.8.0 LTS Released ## TL;DR Dotkernel 1.8.0 (LTS) was released with a new Plugin Architecture, a redesigned and mobile-friendly frontend, APC/File caching for faster response times, a new Dot_Request class, and multiple security and alerting improvements. Some features (WURFL integration, multiple SMTP transporters) were removed from core and made available as plugins instead. ## What is LTS? Long-term support (LTS) is a type of special version or edition of software designed to be supported for a longer than normal period. It's particularly applicable to open-source software projects. The 1.8.0 LTS release itself contains many bug fixes, some refactoring, and a few minor features. ## Highlights of 1.8.0 (LTS) ### Plugin Architecture Starting with 1.8.0, Dotkernel uses Plugins to make extending the framework easier. ### New design The admin module was redesigned and the frontend module is now mobile-friendly, while the separate mobile module remains available. ### Loads faster The framework now supports APC and File Caching, with all XML and config files cached in order to maximize response speed. ### Easier request handling A new class, `Dot_Request`, gives control over the request data before use - for example, so that `$_SERVER`, `$_GET`, and `$_POST` are only accessed from within controllers. ### Features added - API with Rate Limit - a simple API with single-key authentication and a basic rate limit implementation (configurable in `/configs/application.ini`, section `params.api`) - Cache System - built on Zend_Cache backends, providing caching within Dotkernel and in library code ### Other changes - Removed WURFL integration - mobile device detection is now handled separately; WURFL can be added as a plugin - Removed support for multiple SMTP transporters - it can be added as a plugin - Security scan in the Admin Dashboard, showing recommended (especially security-related) settings - Admin failed-login notifications are now sent to all developers listed in `devEmails` (within the `settings` table), not just the first admin - Alert System - alerts can be sent to all developers to notify them if something goes wrong ### Bug fixes - `seo.xml` caused an error when two modules used the same variable name instead of overwriting it - Emails were sent twice - A wrong "unwritable" warning appeared on nginx ## Scale of the release There were a lot of commits in the SVN repository since the previous release, so the blog post only covers the highlights. ## FAQ **Q: What does LTS mean for Dotkernel 1.8.0?** A: LTS stands for Long-term support, a type of special version designed to be supported for longer than normal, which is particularly common for open-source software projects. **Q: What is the Plugin Architecture introduced in 1.8.0?** A: Starting with 1.8.0, Dotkernel uses Plugins to make extending the framework easier. **Q: How does 1.8.0 load faster than previous versions?** A: It supports APC and File Caching within the framework, so XML files and config files are cached to maximize response speed. **Q: What is Dot_Request?** A: Dot_Request is a new class that gives you control over the request data before you use it, so that the variables $_SERVER, $_GET and $_POST are only accessed within controllers. **Q: What was removed from Dotkernel in 1.8.0?** A: WURFL integration was removed (mobile device detection is now handled separately, and WURFL can be added as a plugin), and support for multiple SMTP transporters was removed (it can also be added as a plugin). **Q: What security-related additions does 1.8.0 include?** A: A security scan in the Admin Dashboard shows recommended settings, admin failed-login notifications are sent to all developers listed in devEmails (not just the first admin), and a new Alert System can notify developers if something goes wrong. ## Resources - What is LTS: http://www.dotkernel.com/long-term-support - Caching in Dotkernel using Zend Framework: http://www.dotkernel.com/dotkernel/caching-in-dotkernel-using-zend-framework/ - Dotkernel reserved variable names for caching: http://www.dotkernel.com/dotkernel/dotkernel-reserved-variable-names-for-caching/ - How to use alerts in Dotkernel: http://www.dotkernel.com/dotkernel/how-to-use-alerts-in-dotkernel/ - Dotkernel 1.8.0 (LTS) download: http://www.dotkernel.com/download/?did=41 --- title: "Dotkernel 1.8.1 + Upgrade from 1.8.0 Released" description: "Dotkernel 1.8.1 adds Enhanced Cache Support with cache tagging, and ships with a dedicated upgrade package for users coming from 1.8.0." author: "Gabi DJ" date_published: "2015-06-11" canonical_url: "https://www.dotkernel.com/dotkernel/dotkernel-1-8-1-upgrade-from-1-8-0-released/" category: "Dotkernel" language: "en" --- # Dotkernel 1.8.1 + Upgrade from 1.8.0 Released ## TL;DR Dotkernel 1.8.1 was released with Enhanced Cache Support, allowing cache tags to be used if the hosting environment supports them. A dedicated upgrade package is available for users coming from 1.8.0. ## What's new - Enhanced Cache Support - you can use tags in your cache system if the host supports it ## Download links - Dotkernel 1.8.1 (full package) - Upgrade from Dotkernel 1.8.0 - Dotkernel 1.8.0 (LTS) ## FAQ **Q: What's new in Dotkernel 1.8.1?** A: The main change is Enhanced Cache Support, which means you can use tags in your cache system if the host supports it. **Q: How do I upgrade from 1.8.0 to 1.8.1?** A: The post provides a dedicated "Upgrade from Dotkernel 1.8.0" download link, separate from the full Dotkernel 1.8.1 package and the original Dotkernel 1.8.0 (LTS) download. ## Resources - Dotkernel 1.8.1: http://www.dotkernel.com/download/?did=42 - Upgrade from Dotkernel 1.8.0: http://www.dotkernel.com/download/?did=43 - Dotkernel 1.8.0 (LTS): http://www.dotkernel.com/download/?did=41 --- title: "Dotkernel Coding Standard" description: "Dotkernel borrows the Zend Framework coding standard with a few exceptions, covering indentation, class/interface/file naming, and curly brace placement for control statements." author: "admin" date_published: "2008-03-28" canonical_url: "https://www.dotkernel.com/dotkernel/dotkernel-coding-standard/" category: "Dotkernel" language: "en" --- # Dotkernel Coding Standard ## TL;DR Dotkernel is a "skeleton" of Zend Framework and borrows its coding standard from the ZF Coding Standard, with a small number of exceptions covering indentation, naming conventions, and brace placement. ## Indentation Indentation is made with tabs, not spaces (per section B.2.2 of the Zend Framework Coding Standard). ## Naming conventions Dotkernel uses camel naming conventions, with these Dotkernel-specific rules: | Element | Convention | Example | |---|---|---| | Classes | Start with `Dot_` | `Dot_Templates` | | Interfaces | End with the string "Interface" | `Dot_Db_Interface` | | Filenames | Always use the `.php` extension, no fancy extensions | `.php`, not `.inc` | ## Control statements - brace placement Every opening curly brace `{` starts on its own new line after the statement, and its matching closing brace `}` is also placed on its own new line, aligned in the same column as the opening brace, for better indentation of the code. Example: ```php if ($a != 2) { $a = 2; } ``` ```php if ($a != 2) { $a = 2; if($a == 2) { $c = 3; } } ``` ## FAQ **Q: What coding standard does Dotkernel follow?** A: Dotkernel borrows its coding standard from the Zend Framework Coding Standard, with some exceptions described in this article. **Q: Tabs or spaces for indentation?** A: Dotkernel indents with tabs, not spaces. **Q: How should classes, interfaces, and filenames be named?** A: Classes start with the prefix Dot_ (e.g. Dot_Templates), interfaces end with the string "Interface" (e.g. Dot_Db_Interface), and all PHP files use the ".php" extension, with no fancy extensions like ".inc". **Q: How should curly braces be placed for control statements?** A: Every opening curly brace starts on its own new line after the statement, and its matching closing brace also goes on a new line, aligned in the same column as the opening brace, for better indentation of the code. ## Resources - Zend Framework: http://framework.zend.com/ - ZF Coding Standard: http://framework.zend.com/manual/en/coding-standard.php-file-formatting.html - ZF Coding Standard - Indentation: http://framework.zend.com/manual/en/coding-standard.php-file-formatting.html#coding-standard.php-file-formatting.indentation - ZF Coding Standard - Naming Conventions: http://framework.zend.com/manual/en/coding-standard.naming-conventions.html - ZF Coding Standard - Classes: http://framework.zend.com/manual/en/coding-standard.naming-conventions.html#coding-standard.naming-conventions.classes - ZF Coding Standard - Interfaces: http://framework.zend.com/manual/en/coding-standard.naming-conventions.html#coding-standard.naming-conventions.interfaces - ZF Coding Standard - Filenames: http://framework.zend.com/manual/en/coding-standard.naming-conventions.html#coding-standard.naming-conventions.filenames - ZF Coding Standard - Control Statements: http://framework.zend.com/manual/en/coding-standard.coding-style.html#coding-standard.coding-style.control-statements --- title: "Dotkernel Database Naming Conventions for MySQL" description: "Dotkernel borrows its database naming conventions from FaZend, covering singular table names, auto-incrementing id columns, foreign key and constraint naming patterns, and camelLetter casing." author: "admin" date_published: "2010-03-10" canonical_url: "https://www.dotkernel.com/dotkernel/dotkernel-database-naming-conventions-for-mysql/" category: "Dotkernel" language: "en" --- # Dotkernel Database Naming Conventions for MySQL ## TL;DR Dotkernel's database naming conventions are borrowed from FaZend's "Rules of naming of database tables and columns." Tables use singular, camelLetter names, every table has an auto-increment id, foreign keys are named after the referenced table and column, and SQL keywords are capitalized. ## Database naming conventions for tables and columns - Singular table names only (e.g. `user`, `category`, `product`, `order`, `orderProduct`) - Every table must have an auto-incrementing integer column `id` - ZF-like names of columns and tables (e.g. `user::isAdmin`, `orderProduct::product`) - Foreign keys must have the same name as the referenced table plus the name of the referenced column. Example: table referenced is `admin`, column name `Id`, so the foreign key column will be `adminId`. - Pattern for CONSTRAINT name: `FK_referencedTableName_tableName`. Example: `CONSTRAINT FK_admin_adminLogin`. - SQL keywords are capitalized (e.g. `SELECT`, `INT`) ## Example of proper SQL file formatting and naming ```sql CREATE TABLE IF NOT EXISTS `user` ( `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, `username` VARCHAR(255) NOT NULL, `password` VARCHAR(25) NOT NULL, `email` VARCHAR(100) NOT NULL, `firstName` VARCHAR(255) NOT NULL, `lastName` VARCHAR(255) NOT NULL, `dateCreated` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, `userType` INT(11) NOT NULL AUTO_INCREMENT `isActive` ENUM('0','1') NOT NULL DEFAULT '1', PRIMARY KEY (`id`), UNIQUE KEY `username` (`username`), UNIQUE KEY `email` (`email`) CONSTRAINT `FK_user_userType` FOREIGN KEY(`userTypeId`) REFERENCES `userType`(`id`) ON UPDATE CASCADE ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; ``` ## Conclusion The names of database tables and columns must follow camelLetter naming conventions. ## FAQ **Q: Where do Dotkernel's database naming conventions come from?** A: They are borrowed from FaZend's "Rules of naming of database tables and columns," an open-source PHP framework based on Zend Framework. **Q: Should table names be singular or plural?** A: Singular table names only, for example user, category, product, order, orderProduct. **Q: How should foreign key columns be named?** A: A foreign key column takes the name of the referenced table plus the name of the referenced column. For example, referencing table admin's Id column produces a column named adminId. **Q: What naming pattern is used for CONSTRAINT names?** A: The pattern is FK_referencedTableName_tableName, for example CONSTRAINT `FK_admin_adminLogin`. **Q: What casing convention applies to table/column names and to SQL keywords?** A: Table and column names must follow camelLetter naming conventions, while SQL keywords such as SELECT and INT are capitalized. ## Resources - FaZend: Rules of naming of database tables and columns: http://fazend.com/a/2009-11-DataNaming.html --- 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 ## FAQ **Q: What is Dotkernel Light?** A: Dotkernel Light is a version of Dotkernel Frontend that includes only the bare-bones essentials. It's suitable as a presentation site, an introduction to the Mezzio microframework architecture, or a starting point for a more complex project where you want full control over functionality. **Q: What is the goal of Dotkernel Light?** A: It's designed to be a fast-start example of using the Mezzio microframework as well as an entry-level version of Dotkernel Frontend, presenting the beginner developer with as few moving parts as possible while still letting the more advanced developer have full control of the platform's functionality. **Q: What functionality does Dotkernel Light retain?** A: It keeps routing, templating, error handling, and tests and code quality checks. **Q: What was removed compared to Dotkernel Frontend?** A: Items removed include Doctrine and all database related stuff, sessions/cookies/flash messages, authentication/authorization, dependency injection, mail related stuff, navigation, CORS, forms/validators/input filters, the User module, the Contact module, the Plugin module, unused CSS/JS code, and outdated README instructions. **Q: Which packages are no longer required in Dotkernel Light?** A: Packages such as dotkernel/dot-authorization, dotkernel/dot-mail, dotkernel/dot-session, dotkernel/dot-navigation, dotkernel/dot-flashmessenger, laminas/laminas-form, mezzio/mezzio-cors, and several others used by Frontend are not required. ## 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 `