---
title: "Code Style Guidelines"
url: https://festi.dev/8.0/FAQ/CodeStyle/
---

# Code Style Guidelines

## Spacing Consistency

Avoid skimping on spaces within your code. For instance:
```php
$amount=5;

if(amount>5){
}

foreach($rows as $key=>$value){
}
```
Instead, adhere to consistent spacing like this:

```php
$amount = 5;

if (amount > 5) {
}

foreach ($rows as $key => $value) {
}
```

## Clarity in Naming

Refuse to abbreviate method and variable names, ensuring clarity and understanding:

```php
public function isBtnExists($btn)
{
   ...
}
```

Prefer clear and descriptive names:

```php
public function isButtonExists($buttonName)
{
   ...
}
```

This rule applies to variables as well. Do not use abbreviated variable names:

```php
// Bad
$opt = $this->getOptionsTable();
$val = $this->getValuesTable();

// Good
$optionsTable = $this->getOptionsTable();
$valuesTable = $this->getValuesTable();
```

## Short Array Syntax

Always use short array syntax `[]` instead of `array()`:

```php
// Bad
$values = array('name' => 'test');

// Good
$values = ['name' => 'test'];
```

## Array Formatting for Readability

The main goal is the readability of the code, and everything else is secondary.
Prioritize code readability when defining arrays:

```php
$tabSettings = [
                        "templateFolder"  => "/templates/",
                        "keyInGetArray" =>  $this->keyInGetArray
];
```

Format arrays for clear visibility:

```php
$tabSettings = [
   "templateFolder" => "/templates/",
   "keyInGetArray"  => $this->keyInGetArray
];
```

## Consistent Naming Conventions

Adopt "camel" casing for variables and attributes:

```php
$productAmount
$productIDsToUserID
```

Avoid numerical characters in names; spell out numbers instead:

```php
$usersToType
$modelForProduct
```

## Method Names in Classes

Follow "camel" casing for method names:

```php
getUsers
```

It is also often the case that many duplicate the class name in the method name, the main question is why? 
If your class is named `UserSearch`, then there is no need to name a method `updateUserSearchData` in it; the method should have been named `updateData`.

Always specify the isolation level even if the method is public:

```php
public function setSomething()
{
   ...
}
```

There are also certain rules for forming method names depending on their purpose.

### Standardized Method Naming Conventions

Methods that should handle AJAX requests should start with the prefix `onAjax`: For example: `onAjaxUpdateContactForm`, `onAjaxProductInformation`.

Methods that display XML or JSON data should have a suffix `Xml`, `Json`. For example: `displayUserCartXml`, `displayInventoryJson`.

And there can be combined options, for example, when we send an AJAX request and expect a JSON response: `onAjaxCartListJson`.

#### Methods for Displaying Information

Prefix `display` or `onDisplay` for methods displaying content:
```php 
displaySignupForm
displayMainPage
onDisplayDashboard
```

#### Methods Returning HTML Fragments

Begin `fetch` for methods returning HTML:

```php
fetchUserCart
```

#### Request Processing Methods

These are, for example, form handlers and similar methods, such methods should start with the prefix `do`. 
If the method handler displays information, then the prefix contains its type, for example, `doAjax`, `doJson`, `doXml`.

```php
doAjaxUpdateAdForm
doJsonGroupRemoveAds
doChangeStatus
```

Ensure consistency in response handling:

```php
$response = new Response(Response::JSON);
$response->status = false;
$response->errors = $this->errorMessages;
$response->send();
```

It is important to adhere to the construction of the names of these methods, as the correct handling of Exceptions is determined by them.

#### Methods Perform Logical Checks

The return result of their call is Boolean (`true` / `false`) in most cases. Such methods should start with the prefix `is` or `has`, for example: 
```php
hasUserEmail
isProductExists
```

#### Getter and Setter Methods

In our projects, the use of standard getter and setter methods accepted in PHP is not welcome. All methods that either return the state of an entity or modify it should start with the prefix `get` or `set`. For example:

```php
getContent
setUserEmail
getSystemErrors
```

#### Callbacks and Event Handlers.

If the method is an event handler, its name should start with the prefix `on`:

```php
public function onUserSignIn()
{
   ...
}
```

The same applies to hooks and similar stuff:

```php
add_action('admin_head', [&$this, 'onAdminHeadAction']);
```

### Private and Protected Methods and Attributes

**Private** methods and attributes must be prefixed with an underscore:

```php
$_productsInCart

private function _getUserOrder(): void
{
    // ...
}
```

This makes it immediately visible at the call site (`$this->_getUserOrder()`) that
the method is private to the class and not part of any extension point.

**Protected** methods and attributes do **not** use an underscore prefix:

```php
$productsInCart

protected function getUserOrder()
{

}
```

## Code Block Formatting

The bodies of methods always start on a new line, and all operators start from the current line, for example:

```php
public function hasErrors()
{
 ...
}

if ($this->hasErrors()) {
  ...
} else if ($this->isWork()) {
  ...
} else {
  ...
}
```

### No Inline Methods

Methods must never be written inline. Always use the standard multi-line format:

Incorrect:
```php
public function getDeliveryTag(): int { return $this->deliveryTag; }
```

Correct:
```php
public function getDeliveryTag(): int
{
    return $this->deliveryTag;
}
```

### PHPDoc for Public Methods

All public methods must have a PHPDoc block. See the [Documenting Public Methods](#documenting-public-methods) section for full requirements.

## If Statement Formatting

Writing ifs in the format:

```php
if ($a != 5 && $a > $b || $c > 7) 
```
is forbidden.

One of the most important rules is the readability of the code, and the example above will only be understood by the programmer who wrote it, and even then only for a few days. 
All such conditions should be moved to a separate method and have a logical name, for example:

```php
if ($this->isAllUnitHasWappon($units))
```

If the method name is too long, you can do this:

```php
$result = $this->hasExperienceIntoUserInventory();

if ($result) {

}
```

## Global Usage

Using `global` is prohibited, meaning you cannot write:
```php
global $jimbo;
```

You might say that you encounter such entries in the code, and that's true - it used to be used all the time, but now it is FORBIDDEN!
About what to replace `$jimbo` with is described in the `Working with Core` section.

## Error Logging

Always log errors before returning error responses. Use `FestiUtils::addLogMessage()` to record the error:

```php
try {
    // ...
} catch (Exception $e) {
    FestiUtils::addLogMessage($e->getMessage());
    $response->setStatus(Response::STATUS_INTERNAL_SERVER_ERROR);
}
```

## Returning a List of Errors From a Method

If your method of checking or processing has logic for returning a list of errors, then you need to pass an array (`ArrayObject`) by reference and write errors into it.
If the method does not contain a return logic, then you should return a boolean. For example:

```php
protected function doUpdateProfile(array $formInfo, array $values, ArrayObject &$errors): bool
{
    ...
    
    return true;
}
```

## 120-Character Line Length Limit

The maximum line length is **120 characters**. Method signatures, `fireEvent` calls, and similar expressions that fit within 120 characters should remain on one line — do not split them across multiple lines unnecessarily.

If a line exceeds 120 characters, break it at logical points (see [Writing Calls with Long Method Names](#writing-calls-with-long-method-names-and-multiple-parameters)).

## Closing php Tag

In files with php extensions, if they are not templates, you do not need to close the tag

```php
<?php
```

## Short Echo Tags

Short echo tags (`<?=`) are **not allowed**. Always use the full syntax:

```php
// Bad
<?= $title ?>

// Good
<?php echo $title; ?>
```

## Naming Files

One class one file. That is, if there is a class `User`, it should be in a separate file and named `User.php`.

If your file is application-level (templates, css, images), it should be named: `update_user_data.php`

## Errors in Return Statements.

Often many write such code:

```php
$result = fwrite($file, $content);

if ($result) {
    return true;
}

return false;
```

What differs the above code from:

```php
$result = fwrite($file, $content);

return !empty($result);
```

## Working With Files

Often we see such code:

```php
$file = fopen($filePath, "w");
        
$result = fwrite($file, $content);

fclose($file);

if ($result) {
    return true;
}

return false;
```

In this example, there are at least 3 errors:

1. If you use functions that work with files, streams, sockets, you always need to check the result of their opening:

```php
$file = fopen($filePath, "w");

if ($file === false) {
    throw new Exception("Permission denied: ". $filePath);
}
```

2. The code should be stable or predictable, not introduce chaos in the search for bugs, meaning you need to check the correct execution of function calls, in this case `fwrite`:

```php
$result = fwrite($file, $content);

if ($result === false) {
    throw new Exception("Write error");
}
```

3. There is no need to reinvent the wheel, and it would be easier to write the code above like this:

```php
$result = file_put_contents($filePath, $content);

return $result !== false;
```

That is, if you write the code as in point 3, you deprive yourself of unnecessary hassle with checks, and the argument that `fopen` is faster than `file_put_contents` always brings a smile.

## Class Initialization

When initializing classes, it's necessary to include `()`, like this:

```php
$page = new FaqPage();
```

## Default Parameter Values

Rarely is it necessary to pass an empty string as a default value. 
In most cases, the default value should be `false` or `null`, depending on the parameter type. 
If it's a primitive type, use `false`; if it's an object, use `null`.

In 95% of cases, avoid writing like this:

```php
public function displayInfo(string $key, array $options, string $parameter = ''): bool
{
    ...
    
    return true;
}
```

Instead, use:

```php
public function displayInfo(string $key, array $options, ?string $parameter = null): bool
{
    ...
    
    return true;
}
```

## Abbreviating Parameter Array Names

Avoid using different abbreviations for parameter arrays within the same project. The most common aliases are:

* attrs
* args 
* params 
* parameters 
* arguments 
* options

The first two should generally be avoided altogether.
`Parameters` is unnecessary, as `params` is more suitable for passing parameter arrays. 
`Arguments` should be avoided, as it usually refers to parameters passed when launching the system. 
`Options` typically refers to an array of parameters that affect the behavior of an object, method, or system as a whole, but it is not simply parameters.

## Spaces in Expressions

Use spaces between arithmetic operations but **never** around the `.` concatenation operator:

```php
$a = $b + $c;
$strOne = $strTwo.'append'.$d;
$sql = 'SELECT * FROM '.static::TABLE_NAME;
```

```php
// Bad — spaces around dot
$sql = 'SELECT * FROM ' . static::TABLE_NAME;

// Good — no spaces around dot
$sql = 'SELECT * FROM '.static::TABLE_NAME;
```

## Naming Templates

In Progress

## Naming Variables That Load Entity Data

> *This naming rule applies to data associated with entities, not collections (arrays of entities).*

When fetching data, name variables correctly for immediate understanding of their contents. 
The main naming formats are:

```php
$productData
$productInfo
$productValuesObject
$productValues
```

Understand when and what to name:

`Data` - means that the data is loaded in its raw form as it exists in the database or storage;

```php
$productData = $this->object->get($idProduct);
$productData = $this->plugin->products->load($idProduct);
```

`Info` - when data has been loaded with additional information or has been formatted according to some business logic;

```php
$productInfo = $this->plugin->products->getInfo($idProduct);

...

public function getInfo(int $idProduct): array
{
    $info = $this->object->get($idProduct);
    $info['coupon'] = $this->object->getCoupon($idProduct);
    $info['owner'] = $this->plugin->user->load($info['id_owner']);
    
    return $info;
}
```

`ValuesObject` - when you have a `ValuesObject` object through which you obtain data;

```php
$productData = $this->object->get($idProduct);
$productValuesObject = new ProductValuesObject($productData);
...
$productValuesObject = $this->plugin->products->loadValuesObject($idProduct);
```

`Values` - this is an array that is formed for updating or adding data to the database;

```php
$productValues = [
    'id_owner' => $this->getUserID(),
    'price'  => $price
    ...
];

$this->object->add($productValues);
```

> *This rule also applies to simple variables: `$info`, `$data`, `$values`, `$objectValues`*

## Writing Calls with Long Method Names and Multiple Parameters

If a method or function call is longer than 120 characters, for example:

```php
update_post_meta($idPost, WooCommerceProductValuesObject::PRODUCT_REGULAR_PRICE_KEY, '1');
```

write it like this:

```php
update_post_meta(
    $idPost, 
    WooCommerceProductValuesObject::PRODUCT_REGULAR_PRICE_KEY, 
    '1'
);
```

## Naming Variables and Methods with IDs

All variables containing `ID` indications should be prefixed with id:

```php
$idUser = $this->getUserID();
$idProduct = $this->_getProductID();
```

If there is an indication that this array contains `IDs`, then move `ID` to the postfix by adding the letter "s":

```php
$usersIDs = $this->loadAllUsersIDs();
$productsIDs = $this->_getProductIDs();
```

In method names, we move `ID` to the postfix:

```php
$this->getUserID();
$this->setUserID($idUser);

$this->getUserIDs();
$this->setUserIDs(...);
```

## Using Acronyms in SQL Queries

Avoid using abbreviations for table names to avoid confusing logic and complicating code readability.

Incorrect:

```php
$sql = "SELECT 
               id_account, from_label, from_name, from_company_name, 
               from_phone_number, from_street, from_city, from_state, 
               from_zip, carrier_name
        FROM company_settings
            JOIN carrier_addresses as cd
                ON cd.ident = company_settings.id_carrier
            JOIN companies as co
                ON co.ident = company_settings.id_company 
            JOIN carrier_types as ct
                ON ct.ident = company_settings.id_carrier_type";
```

Correct:

```php
$sql = "SELECT 
               id_account, from_label, from_name, from_company_name, 
               from_phone_number, from_street, from_city, from_state, 
               from_zip, carrier_name
        FROM company_settings
            JOIN carrier_addresses 
                ON (carrier_addresses.ident = company_settings.id_carrier)
            JOIN companies
                ON (companies.ident = company_settings.id_company)
            JOIN carrier_types
                ON (carrier_types.ident = company_settings.id_carrier_type)";
```

## Methods That Perform Checks

Methods that perform checks should have a prefix `verify`, for example:

```php
public function verifyUserPermission(UserValuesObject $userValuesObject):void
{
  ...
}
```

## Methods That Prepare Data by Reference

Methods that prepare, format, or supplement data by reference should have a prefix `prepare`:

```php
private function _prepareTimesheetRow(array &$row): void
{
  ...
}
```

## Event Class

We adhere to the practice of using constructors instead of associative arrays in events. 
Below is an example of our recommended approach:

```php

class BeforeLoadProductEvent
{
    public const TYPE = 'before_load_product';
    
    protected IProduct $product;
    
    public function __construct(IProduct $product) 
    {
        $this->product = $product;
        
        parent::__construct(static::TYPE);
    }
    
    public function &getProduct(): IProduct
    {
        return $this->product;
    }
}

```

## Interface Method Parameters

When defining interfaces, avoid using generic parameter names like `$search` that require consumers to guess what data structure or format is expected.

Instead, define specific methods with specific, well-typed parameters that clearly indicate their purpose and structure.

Incorrect:

```php
interface IUserFacade
{
    public function find(array $search): ?User;
}
```

Correct:

```php
interface IUserFacade
{
    public function findByID(int $idUser): ?User;
    
    public function findByEmail(string $email): ?User;
    
    public function findByUsername(string $username): ?User;
}
```

This approach provides:
- Clear method contracts with explicit parameter types
- Better IDE autocomplete and type checking
- Self-documenting code that doesn't require guessing parameter structure
- Easier refactoring and maintenance

## Separate Actions

When writing code, it's important to split actions onto separate lines. 
This practice enhances readability and simplifies debugging and error logging.

Avoid combining actions on a single line:

```php
$result[] = (new MysqlColumnConvertor($columnOptions))->convert();
```

Instead, split actions onto separate lines:

```php
$convertor = new MysqlColumnConvertor($columnOptions);

$result[] = $convertor->convert();
```

By separating the instantiation and method call, you make the code easier to read and debug.
If an error occurs, it's clearer whether the issue lies in the object creation or the method execution.

The same rule applies to nested `new` expressions passed as constructor arguments:

Incorrect:

```php
$datetime = new DateTime($value, new DateTimeZone($timezone));
```

Correct:

```php
$timeZone = new DateTimeZone($timezone);
$datetime = new DateTime($value, $timeZone);
```

Nesting `new` inside another constructor call hides what objects are being created
and makes the code harder to read and debug.

## Plugin Structure and Naming Conventions

Our projects utilize a plugin-based structure.
Plugins are organized in separate folders within the main `plugins` directory.
Each plugin may contain a `Domain` folder where different logical components are placed in their respective subfolders.

See [Plugin Architecture](https://festi.dev/8.0/Core/Plugins/index.md) for the full plugin layout and lifecycle rules.

### Folder and Namespace Naming

When naming folders and namespaces within the plugin structure, adhere to the following guidelines:

1. Plugin folder name: matches the plugin class name **without** the `Plugin` suffix, in `PascalCase`. For example, `HumanResourcesPlugin` lives in `plugins/HumanResources/`.
2. Domain subfolders (logical code components such as `Domain`, `Model`, `Service`, `Event`, `Listener`, `Store`): use `PascalCase`.
3. Framework-reserved asset folders (`static`, `templates`): use lowercase — these are recognised by the framework by name.
4. Namespaces: must begin with `Plugins\` (note the capital `P` and the trailing `s`, mirroring the `plugins/` root) followed by segments that exactly match the folder names on disk (PSR-4).

Example folder structure:

```
...
- plugins
    - HumanResources
        - Domain
            - Event
            - Listener
            - Model
            - Store
        - static
            - css
            - js
        - templates
        - HumanResourcesPlugin.php
        - HumanResourcesObject.php
        - init.php
```

Corresponding namespace structure:

```php
namespace Plugins\HumanResources;
namespace Plugins\HumanResources\Domain\Event;
namespace Plugins\HumanResources\Domain\Listener;
namespace Plugins\HumanResources\Domain\Model;
namespace Plugins\HumanResources\Domain\Store;
```


## Defining Constants for Repeated Array Keys

When an associative array key or string literal is used more than three times in the code, define it as a class constant (or global constant if appropriate).

This prevents the use of magic strings, reduces typos, and makes code easier to maintain.

Incorrect:

```php
$user['status'] = 'active';

if ($user['status'] === 'active') {
    $this->logActivity($user['status']);
}
```

Correct:

```php
class UserValuesObject extends ValuesObject
{
    public const STATUS_KEY = 'status';
    public const STATUS_ACTIVE = 'active';
}

$user[UserValues::STATUS_KEY] = UserValues::STATUS_ACTIVE;

if ($user[UserValues::STATUS_KEY] === UserValues::STATUS_ACTIVE) {
    $this->logActivity($user[UserValues::STATUS_KEY]);
}
```

Best Practice:

- Always replace strings used more than three times with a constant.
- Keep constants logically grouped (e.g., inside the related class, or in a dedicated constants class).
- Prefer `public const` inside classes over `define()` for better namespacing and type safety.

## Documenting Public Methods

Every public method must include a docblock that explains both what the method does and how it should be used.

This ensures clarity for developers and consistent maintainability.

Requirements:

- Start with a short description of the method’s purpose (what it does).
- Follow with usage details or context (how to use it, when to call it, or what it affects).
- Always include `@param` and `@return` annotations with clear type hints.
- When a method returns an array of objects, use the `Type[]` hinting format.
- Mention side effects (e.g., modifies state, dispatches events, throws exceptions).
- **Describe business purpose, not code mechanics.**

### PHPDoc Format

Every docblock must follow proper PHPDoc format with `@param`, `@return`, and `@throws` annotations:

```php
/**
 * Validates and updates the user’s profile data.
 *
 * This method should be called from the profile update form handler.
 * It writes errors into the $errors array reference if validation fails.
 *
 * @param array $formInfo Raw form data submitted by the user
 * @param array $values Processed values ready for persistence
 * @param ArrayObject $errors Reference for collecting validation errors
 * @return bool Returns true if the profile was updated successfully
 * @throws SystemException When the user does not have permission
 */
public function doUpdateProfile(array $formInfo, array $values, ArrayObject &$errors): bool
{
    ...
}
```

### Return Type Hinting for Arrays of Objects

When a method returns an array of objects, use `Type[]` in the `@return` annotation:

```php
/**
 * Loads all active users for the given company.
 *
 * @param int $idCompany Company identifier
 * @return UserValuesObject[] List of active user value objects
 */
public function getActiveUsers(int $idCompany): array
{
    ...
}
```

### Business-Level Descriptions

PHPDoc descriptions should explain business logic and use cases, not implementation details:

Bad — describes code mechanics:

```php
/**
 * DAO for the contact_us table. Centralises every SQL touch-point so the
 * service layer can stay free of raw query strings...
 */
```

Good — describes business purpose:

```php
/**
 * Provides persistence for contact form submissions. Supports creating,
 * reading, updating, and deleting contact records so operators can triage
 * incoming enquiries...
 */
```

### Best Practice

- Keep descriptions concise but informative.
- Do not duplicate the method name in the description.
- Required for all public methods; optional for private/protected methods (document only if non-trivial).


## Avoid Inline Complex Expressions in Method Calls

Do not pass complex expressions (such as array access, null coalescing, or
chained calls) directly into method arguments. Instead, extract intermediate
values into clearly named variables.

Incorrect:

```php
$reCaptchaResult = $this->getReCaptchaFacade()->validateLeadToken(
    $request->getValues()['recaptcha_token'] ?? null
);
```

Correct:

```php
$values = $request->getValues();
$token = $values['recaptcha_token'] ?? null;

$reCaptchaResult = $this->getReCaptchaFacade()->validateLeadToken($token);
```

Why:

- Improves readability by breaking down complex logic into smaller steps
- Makes debugging easier — you can inspect intermediate variables
- Avoids repeated method calls (e.g., `getValues()`)
- Clarifies intent through meaningful variable names
- Simplifies future refactoring and testing

## Fully Qualified Class Names in Code

Do not use fully qualified class names with a leading backslash inline in code.
Instead, declare a `use` statement at the top of the file.

Incorrect:

```php
} catch (\Throwable $exception) {
    ...
}
```

Correct:

```php
use Throwable;

...

} catch (Throwable $exception) {
    ...
}
```

This applies to any class, interface, or built-in type used inline — not just
exception types. Keeping all dependencies declared at the top of the file makes
imports visible at a glance and keeps the code body clean.

# Conclusion

> And remember the most important rule when writing code: cleanliness is not where you clean up, but where you don't litter!
