Annotations Reference

Last updated: 2026-10-31

Reference for Canvas framework annotations. Annotations configure routing, aspect-oriented programming, and controller configuration.

Routing Annotations

@Route

Purpose: Defines HTTP routes in controller methods.

/**
 * @Route("/users/{id}", methods={"GET", "PUT", "DELETE"})
 */
public function edit(int $id) { ... }

Parameters:

ParameterTypeRequiredDescription
valuestringYesURL pattern with optional {placeholders}
methodsarrayNoHTTP methods (default: ["GET"])
fallbackstringNoFallback path when the configured route cannot be resolved

@RoutePrefix

Purpose: Automatically prefixes all routes in a controller class with a common path segment. Useful for API versioning or grouping related endpoints.

Use When: Multiple routes in a controller share a common path prefix (e.g., "/api", "/v1", "/admin").

/**
 * @RoutePrefix("/api/v1")
 */
class ProductController extends BaseController {

    /**
     * @Route("/products")
     * Final route: /api/v1/products
     */
    public function index() { ... }

    /**
     * @Route("/products/{id}")
     * Final route: /api/v1/products/{id}
     */
    public function show(int $id) { ... }
}

Parameters:

ParameterTypeRequiredDescription
valuestringYesPath prefix to prepend to all routes in the controller (leading/trailing slashes are automatically normalized)

Aspect-Oriented Programming

@InterceptWith

Purpose: Applies cross-cutting concerns (caching, auth, logging) to controller methods or entire classes. Multiple aspects can be stacked.

/**
 * @InterceptWith(CacheAspect::class, ttl=300, tags={"reports", "admin"})
 * @InterceptWith(RequireAuthAspect::class)
 */
public function reports() { ... }

Parameters:

ParameterTypeRequiredDescription
classstringYesFully qualified aspect class name (e.g., CacheAspect::class)
...parametersmixedNoAdditional named parameters passed to aspect constructor

Common Aspect-Specific Parameters:

ParameterTypeUsed ByDescription
ttlintCacheAspectCache time-to-live in seconds
tagsarrayCacheAspectCache invalidation tags for grouped clearing
limitintRateLimitAspectMaximum requests allowed in time window
windowintRateLimitAspectTime window in seconds for rate limiting
permissionstringRequirePermissionAspectRequired authorization permission string

Cache Configuration

@CacheContext

Purpose: Configures cache behavior for methods that inject CacheInterface — namespace and driver-specific connection parameters. Selecting which driver gets injected is @WithContext's job, not @CacheContext's; see Contextual Containers (DI).

Use When: Different methods need isolated cache namespaces, or a method's driver varies (e.g., Redis for sessions, file cache for temporary data) and each driver needs its own namespace or connection override.

class ProductService {

    /**
     * Uses the configured default driver with the 'products' namespace
     * @CacheContext(namespace="products")
     */
    public function getProducts(CacheInterface $cache): array {
        return $cache->remember('all_products', 3600, function() {
            return $this->repository->findAll();
        });
    }

    /**
     * Uses file cache with a custom namespace
     * @WithContext(parameter="cache", context="file")
     * @CacheContext(namespace="temp_reports")
     */
    public function generateReport(CacheInterface $cache): string {
        return $cache->get('report_123');
    }

    /**
     * Uses Redis with custom connection config
     * @WithContext(parameter="cache", context="redis")
     * @CacheContext(namespace="sessions", host="session-redis.local", port=6380)
     */
    public function getSession(CacheInterface $cache, string $sessionId): ?array {
        return $cache->get("session_{$sessionId}");
    }
}

Parameters:

ParameterTypeRequiredDescription
contextstringNoTies this instance to the value @WithContext resolves to. @CacheContext is repeatable — add one per context the method's @WithContext can resolve to, plus an untagged instance (omit context) as the default used when none of the tagged ones match.
namespacestringNoCache namespace for key isolation (default: "default"). Useful for separating cache concerns (e.g., "sessions", "products", "temp").
...custommixedNoDriver-specific configuration parameters (e.g., host, port, database for Redis; servers for Memcached). These override config/cache.php settings for this method.

Configuration Priority:

The driver itself is selected by @WithContext's context tag (falling back to the configured default when no @WithContext is present). Once a driver is chosen, its configuration values are resolved in the following order (later sources override earlier ones):

  1. Default driver configuration from config/cache.php
  2. The matching @CacheContext annotation's parameters
  3. Runtime parameters passed to Container::get(CacheInterface::class, $params)

Complete Controller Example

/**
 * API v1 Product Controller
 * All routes automatically prefixed with /api/v1
 *
 * @RoutePrefix("/api/v1")
 * @InterceptWith(RequireAuthAspect::class)
 * @InterceptWith(AuditLogAspect::class)
 */
class ProductController extends BaseController {

    /**
     * List all products (cached for 5 minutes)
     * Final route: GET /api/v1/products
     *
     * @Route("/products", methods={"GET"})
     * @InterceptWith(CacheAspect::class, ttl=300, namespace="products")
     */
    public function index() {
        return $this->productRepository->findAll();
    }

    /**
     * View single product (cached for 10 minutes)
     * Final route: GET /api/v1/products/{id}
     *
     * @Route("/products/{id}", methods={"GET"})
     * @InterceptWith(CacheAspect::class, ttl=600, namespace="products")
     */
    public function show(int $id) {
        return $this->productRepository->find($id);
    }

    /**
     * Create new product (requires permission, wrapped in transaction)
     * Final route: POST /api/v1/products
     *
     * @Route("/products", methods={"POST"})
     * @InterceptWith(RequirePermissionAspect::class, permission="products.create")
     * @InterceptWith(TransactionAspect::class)
     */
    public function create() {
        $product = $this->productRepository->create($this->request->all());
        return $this->created($product);
    }

    /**
     * Update product (requires permission, wrapped in transaction, rate limited)
     * Final route: PUT /api/v1/products/{id}
     *
     * @Route("/products/{id}", methods={"PUT"})
     * @InterceptWith(RequirePermissionAspect::class, permission="products.edit")
     * @InterceptWith(TransactionAspect::class)
     * @InterceptWith(RateLimitAspect::class, limit=60, window=3600)
     */
    public function update(int $id) {
        $product = $this->productRepository->update($id, $this->request->all());
        return $this->success($product);
    }

    /**
     * Delete product (requires permission, wrapped in transaction)
     * Final route: DELETE /api/v1/products/{id}
     *
     * @Route("/products/{id}", methods={"DELETE"})
     * @InterceptWith(RequirePermissionAspect::class, permission="products.delete")
     * @InterceptWith(TransactionAspect::class)
     */
    public function delete(int $id) {
        $this->productRepository->delete($id);
        return $this->noContent();
    }
}