### Install Yaf Extension Source: https://github.com/laruence/yaf/blob/master/README.md Methods to install the Yaf PHP extension via PECL or manual compilation from source. ```bash $pecl install yaf ``` ```bash $/path/to/phpize $./configure --with-php-config=/path/to/php-config $make && make install ``` -------------------------------- ### Implement Controller and View Source: https://github.com/laruence/yaf/blob/master/README.md Example of a Yaf controller action and its corresponding PHP-based view template. ```php getView()->content = "Hello World"; } } ``` ```html Hello World ``` -------------------------------- ### Handle HTTP Requests with Yaf_Request_Http Source: https://context7.com/laruence/yaf/llms.txt Illustrates how to use Yaf_Request_Http for managing incoming HTTP requests. It covers creating request objects, checking request methods (GET, POST, AJAX, CLI, etc.), retrieving various types of request data (query, post, cookie, files, server, env), accessing routing information (module, controller, action), and manipulating URI and route parameters. Includes an example of a simple request object for testing. ```php isGet()) { /* handle GET */ } if ($request->isPost()) { /* handle POST */ } if ($request->isPut()) { /* handle PUT */ } if ($request->isDelete()) { /* handle DELETE */ } if ($request->isHead()) { /* handle HEAD */ } if ($request->isPatch()) { /* handle PATCH */ } if ($request->isOptions()) { /* handle OPTIONS */ } if ($request->isCli()) { /* CLI request */ } if ($request->isXmlHttpRequest()) { /* AJAX request */ } // Get request data $id = $request->getQuery("id"); // $_GET["id"] $name = $request->getPost("name"); // $_POST["name"] $cookie = $request->getCookie("session"); // $_COOKIE["session"] $file = $request->getFiles("upload"); // $_FILES["upload"] $server = $request->getServer("HTTP_HOST"); // $_SERVER["HTTP_HOST"] $env = $request->getEnv("APP_ENV"); // $_ENV["APP_ENV"] $any = $request->get("key"); // Search all sources $raw = $request->getRaw(); // Raw request body // With default values $page = $request->getQuery("page", 1); $limit = $request->getPost("limit", 10); // Routing information $module = $request->getModuleName(); $controller = $request->getControllerName(); $action = $request->getActionName(); $method = $request->getMethod(); // URI handling $baseUri = $request->getBaseUri(); $requestUri = $request->getRequestUri(); $request->setBaseUri("/app"); $request->setRequestUri("/user/list"); // Route parameters $request->setParam("id", 123); $id = $request->getParam("id"); $params = $request->getParams(); $request->clearParams(); // Simple request for testing/CLI $simple = new Yaf_Request_Simple("GET", "Index", "User", "profile", array("id" => 123)); ``` -------------------------------- ### Yaf_Registry: Global Data Storage Source: https://context7.com/laruence/yaf/llms.txt Illustrates how to use Yaf_Registry as a global singleton to store and retrieve application-wide data. It covers setting, getting, checking for existence, and deleting registry entries. ```php true, "env" => "production")); Yaf_Registry::set("logger", new MyLogger()); // Retrieve values $db = Yaf_Registry::get("db"); $config = Yaf_Registry::get("config"); $debug = Yaf_Registry::get("config")["debug"]; // Check existence if (Yaf_Registry::has("cache")) { $cache = Yaf_Registry::get("cache"); } else { $cache = new MyCache(); Yaf_Registry::set("cache", $cache); } // Delete entry Yaf_Registry::del("temp_data"); // Common use cases class IndexController extends Yaf_Controller_Abstract { public function indexAction() { // Access registered services $db = Yaf_Registry::get("db"); $stmt = $db->prepare("SELECT * FROM users WHERE id = ?"); $stmt->execute(array($this->getRequest()->getQuery("id"))); $user = $stmt->fetch(PDO::FETCH_ASSOC); $this->getView()->assign("user", $user); } } ``` -------------------------------- ### Yaf_Session: Session Management Wrapper Source: https://context7.com/laruence/yaf/llms.txt Shows how to manage PHP sessions using Yaf_Session, offering both object-oriented and array-style access. It covers starting, setting, getting, checking, deleting, clearing, iterating, and counting session data. ```php start(); // Set values $session->set("user_id", 123); $session->set("username", "john"); $session["role"] = "admin"; // ArrayAccess $session->preferences = array( // Magic setter "theme" => "dark", "language" => "en" ); // Get values $userId = $session->get("user_id"); $username = $session["username"]; // ArrayAccess $role = $session->role; // Magic getter $all = $session->get(); // Get all // Check existence if ($session->has("user_id")) { // User is logged in } $exists = isset($session["username"]); // ArrayAccess // Delete values $session->del("temp_token"); unset($session["flash_message"]); // ArrayAccess // Clear all session data $session->clear(); // Iteration foreach ($session as $key => $value) { echo "$key: " . print_r($value, true) . "\n"; } // Count entries $count = count($session); // Common authentication pattern class AuthController extends Yaf_Controller_Abstract { public function loginAction() { $session = Yaf_Session::getInstance()->start(); if ($this->getRequest()->isPost()) { $username = $this->getRequest()->getPost("username"); $password = $this->getRequest()->getPost("password"); // Validate credentials... if ($valid) { $session->set("user_id", $user["id"]); $session->set("username", $user["username"]); $this->redirect("/dashboard"); } } } public function logoutAction() { Yaf_Session::getInstance()->clear(); $this->redirect("/"); } } ``` -------------------------------- ### Manage HTTP Responses with Yaf_Response_Http Source: https://context7.com/laruence/yaf/llms.txt Details the usage of Yaf_Response_Http for constructing and sending HTTP responses. It covers setting and appending/prepending body content, managing named body segments, clearing body content, setting HTTP headers (including status codes and replacement options), retrieving headers, clearing all headers, and performing redirects. The example also shows how to send the response and convert it to a string. ```php getResponse(); // Set response body $response->setBody("Hello World"); $response->setBody("Content for footer", "footer"); // Append/prepend body content $response->appendBody("

Additional content

"); $response->prependBody("
Header content
"); // Named body segments $response->setBody("Main content", "content"); $response->appendBody("Footer", "footer"); $content = $response->getBody("content"); $allBody = $response->getBody(); // All segments concatenated // Clear body $response->clearBody(); // Clear all $response->clearBody("footer"); // Clear specific segment // HTTP headers (Yaf_Response_Http) $httpResponse = new Yaf_Response_Http(); $httpResponse->setHeader("Content-Type", "application/json"); $httpResponse->setHeader("X-Custom-Header", "value", true); // Replace existing $httpResponse->setHeader("Location", "/login", false, 302); // With status code $contentType = $httpResponse->getHeader("Content-Type"); $allHeaders = $httpResponse->getHeader(); // Get all headers $httpResponse->clearHeaders(); // Redirect $httpResponse->setRedirect("/user/profile"); // Send response $httpResponse->response(); // Convert to string $output = (string)$response; ``` -------------------------------- ### Initialize and Run Yaf Application Source: https://context7.com/laruence/yaf/llms.txt Demonstrates how to create and bootstrap a Yaf application using either an INI configuration file or an array. It covers accessing application singletons and executing custom callbacks. ```php array( "directory" => APPLICATION_PATH . "/application/", "dispatcher" => array( "catchException" => true, "throwException" => true, ), ), ); $app = new Yaf_Application($config); // Bootstrap and run $app->bootstrap()->run(); // Access application singleton $instance = Yaf_Application::app(); $dispatcher = $instance->getDispatcher(); $config = $instance->getConfig(); $modules = $instance->getModules(); // Error handling $errorNo = $instance->getLastErrorNo(); $errorMsg = $instance->getLastErrorMsg(); $instance->clearLastError(); // Execute custom callback $result = $app->execute(function($arg1, $arg2) { return $arg1 + $arg2; }, 1, 2); ``` -------------------------------- ### Render Templates with Yaf_View_Simple Source: https://context7.com/laruence/yaf/llms.txt Demonstrates how to initialize the Yaf_View_Simple engine, assign variables by value or reference, and render or display template files. It also covers template path management and evaluating raw template strings. ```php $view = new Yaf_View_Simple("/path/to/views", array("ext" => "phtml")); $view->assign("title", "My Page"); $view->assignRef("data", $data); $html = $view->render("index.phtml"); $view->display("index.phtml"); $result = $view->eval("

", array("title" => "Hello")); ``` -------------------------------- ### Initialize Application with Yaf_Bootstrap_Abstract Source: https://context7.com/laruence/yaf/llms.txt Demonstrates how to extend Yaf_Bootstrap_Abstract to initialize application resources. Methods prefixed with '_init' are automatically invoked by the framework during the bootstrap process to configure dependencies like databases, routes, and views. ```php getConfig(); Yaf_Registry::set("config", $config); } public function _initDatabase(Yaf_Dispatcher $dispatcher) { $config = Yaf_Registry::get("config"); $db = new PDO( "mysql:host=" . $config->database->host . ";dbname=" . $config->database->name, $config->database->user, $config->database->pass ); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); Yaf_Registry::set("db", $db); } public function _initPlugins(Yaf_Dispatcher $dispatcher) { // Register application plugins $dispatcher->registerPlugin(new AuthPlugin()); $dispatcher->registerPlugin(new LogPlugin()); } public function _initRoutes(Yaf_Dispatcher $dispatcher) { // Add custom routes $router = $dispatcher->getRouter(); $router->addRoute("api", new Yaf_Route_Rewrite( "/api/:version/:resource/:id", array("controller" => "Api", "action" => "handle") )); $router->addRoute("blog", new Yaf_Route_Regex( "#^/blog/(\\d{4})/(\\d{2})/([^/]+)$#", array("controller" => "Blog", "action" => "view"), array(1 => "year", 2 => "month", 3 => "slug") )); } public function _initView(Yaf_Dispatcher $dispatcher) { // Configure view $view = new Yaf_View_Simple(APPLICATION_PATH . "/application/views"); $dispatcher->setView($view); // Assign global view variables $view->assign("siteName", "My Application"); $view->assign("version", "1.0.0"); } public function _initSession(Yaf_Dispatcher $dispatcher) { // Start session Yaf_Session::getInstance()->start(); } } // Entry point (public/index.php) define("APPLICATION_PATH", dirname(dirname(__FILE__))); $app = new Yaf_Application(APPLICATION_PATH . "/conf/application.ini"); $app->bootstrap()->run(); ``` -------------------------------- ### Configure Yaf_Dispatcher for Request Lifecycle Management Source: https://context7.com/laruence/yaf/llms.txt Demonstrates how to instantiate and configure the Yaf_Dispatcher singleton to manage the request dispatch cycle, including setting default routes, configuring view rendering, handling responses and exceptions, registering plugins, and performing manual dispatching. It also shows how to access core components like the router, request, response, and application instance. ```php setDefaultModule("Index") ->setDefaultController("Index") ->setDefaultAction("index"); // View configuration $dispatcher->enableView(); // Enable auto-render $dispatcher->disableView(); // Disable auto-render $dispatcher->autoRender(false); // Toggle auto-render // Initialize custom view $view = $dispatcher->initView("/path/to/templates", array("ext" => "phtml")); $dispatcher->setView($view); // Response handling $dispatcher->returnResponse(true); // Return response instead of sending $dispatcher->flushInstantly(false); // Buffer output // Exception handling $dispatcher->throwException(true); $dispatcher->catchException(true); // Custom error handler $dispatcher->setErrorHandler(function($errno, $errstr, $errfile, $errline) { error_log("Error [$errno]: $errstr in $errfile on line $errline"); }, E_ALL); // Register plugin $dispatcher->registerPlugin(new MyPlugin()); // Manual dispatch $request = new Yaf_Request_Simple("GET", "Index", "User", "profile"); $response = $dispatcher->dispatch($request); // Access components $router = $dispatcher->getRouter(); $request = $dispatcher->getRequest(); $response = $dispatcher->getResponse(); $app = $dispatcher->getApplication(); ``` -------------------------------- ### Configure Yaf Application Source: https://github.com/laruence/yaf/blob/master/README.md Demonstrates configuration using an INI file or a PHP array to define application settings. ```ini [product] application.directory = APPLICATION_PATH "/application/" ``` ```php array( "directory" => application_path . "/application/", ), ); $app = new yaf_application($config); ``` -------------------------------- ### Bootstrap Application Entry Source: https://github.com/laruence/yaf/blob/master/README.md Initializes the Yaf application using a configuration file and executes the bootstrap process. ```php bootstrap() ->run(); ``` -------------------------------- ### Configure Routing Strategies in Yaf Source: https://context7.com/laruence/yaf/llms.txt Demonstrates how to initialize Yaf_Router and register various route types including regex, rewrite, map, and simple routing. It also shows how to load routes via configuration arrays and perform reverse routing. ```php $router = new Yaf_Router(); $regexRoute = new Yaf_Route_Regex( "#^/product/(\\d+)/?$#", array("controller" => "Product", "action" => "detail"), array(1 => "id"), array(), "/product/%d" ); $router->addRoute("product_detail", $regexRoute); $rewriteRoute = new Yaf_Route_Rewrite( "/user/:name/:id", array("controller" => "User", "action" => "profile"), array("id" => "\\d+") ); $router->addRoute("user_profile", $rewriteRoute); $mapRoute = new Yaf_Route_Map(true, "_"); $router->addRoute("map", $mapRoute); $simpleRoute = new Yaf_Route_Simple("m", "c", "a"); $router->addRoute("simple", $simpleRoute); $supervarRoute = new Yaf_Route_Supervar("r"); $router->addRoute("supervar", $supervarRoute); $router->addConfig(array( "blog" => array( "type" => "regex", "match" => "#^/blog/(\\d{4})/(\\d{2})/(.+)$#", "route" => array("controller" => "Blog", "action" => "view"), "map" => array(1 => "year", 2 => "month", 3 => "slug") ) )); $request = new Yaf_Request_Http("/product/123"); $router->route($request); ``` -------------------------------- ### Manage Application Configuration with Yaf Source: https://context7.com/laruence/yaf/llms.txt Explains how to load and manipulate configuration settings using Yaf_Config_Ini for file-based settings with inheritance and Yaf_Config_Simple for dynamic, read-write array configurations. ```php $config = new Yaf_Config_Ini("/path/to/application.ini", "production"); $directory = $config->application->directory; $dbHost = $config->database->host; $configArray = $config->toArray(); $simpleConfig = new Yaf_Config_Simple(array( "database" => array("host" => "localhost", "port" => 3306), "cache" => array("enabled" => true) )); $simpleConfig->database->host = "new-host"; $simpleConfig->set("cache.ttl", 7200); foreach ($config->database as $key => $value) { echo "$key: $value\n"; } ``` -------------------------------- ### Yaf_Loader: Class Autoloading and Library Path Management Source: https://context7.com/laruence/yaf/llms.txt Demonstrates how to use Yaf_Loader for automatic class loading, registering local namespaces with custom paths, and managing library paths. It supports PSR-0 conventions and manual file imports. ```php registerLocalNamespace("MyApp", "/path/to/myapp"); $loader->registerLocalNamespace(array( "Vendor" => "/path/to/vendor", "Plugin" => "/path/to/plugins" )); // Get registered namespaces $namespaces = $loader->getLocalNamespace(); // Check if class is local $isLocal = $loader->isLocalName("MyApp_Service_User"); // Clear namespace registrations $loader->clearLocalNamespace(); // Library path management $loader->setLibraryPath("/new/local/library"); $loader->setLibraryPath("/new/global/library", true); // Global $localPath = $loader->getLibraryPath(); $globalPath = $loader->getLibraryPath(true); // Manual class loading $loaded = $loader->autoload("MyApp_Model_User"); // Import file directly Yaf_Loader::import("/path/to/file.php"); // Class naming conventions: // MyApp_Model_User -> /library/MyApp/Model/User.php // With yaf.name_suffix=1: UserModel -> /models/User.php // With yaf.use_namespace=1: \MyApp\Model\User -> /library/MyApp/Model/User.php ``` -------------------------------- ### Configure Web Server Rewrite Rules Source: https://github.com/laruence/yaf/blob/master/README.md Server configuration snippets to route all requests to the Yaf index.php entry point. ```apache RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule .* index.php ``` ```nginx server { listen ****; server_name domain.com; root document_root; index index.php index.html index.htm; if (!-e $request_filename) { rewrite ^/(.*) /index.php/$1 last; } } ``` ```lighttpd $HTTP["host"] =~ "(www.)?domain.com$" { url.rewrite = ( "^/(.+)/?$" => "/index.php/$1", ) } ``` -------------------------------- ### Implement Request Lifecycle Hooks with Yaf_Plugin_Abstract Source: https://context7.com/laruence/yaf/llms.txt Shows how to extend Yaf_Plugin_Abstract to hook into various stages of the request dispatch lifecycle, such as router startup, dispatch loop startup, and post-dispatch. This is useful for implementing cross-cutting concerns like authentication, logging, and header manipulation. ```php class AuthPlugin extends Yaf_Plugin_Abstract { public function routerStartup(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response) { error_log("Router starting: " . $request->getRequestUri()); return true; } public function dispatchLoopStartup(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response) { // Logic for authentication redirection return true; } public function dispatchLoopShutdown(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response) { $response->setHeader("X-Powered-By", "Yaf"); return true; } } $app->getDispatcher()->registerPlugin(new AuthPlugin()); ``` -------------------------------- ### Yaf Controller Base Class and Actions Source: https://context7.com/laruence/yaf/llms.txt Illustrates the usage of Yaf_Controller_Abstract for creating controllers, handling requests and responses, managing views, and performing actions like forwarding, redirecting, and rendering. ```php getRequest(); $response = $this->getResponse(); // Access request data $id = $request->getQuery("id", 0); $name = $request->getPost("name", "default"); // Get view and assign variables $view = $this->getView(); $view->assign("title", "Welcome"); $view->assign("content", "Hello World"); // Or use initView with options $this->initView(array("ext" => "phtml")); // Controller info $moduleName = $this->getModuleName(); $controllerName = $this->getName(); } public function detailAction() { // Forward to another action $this->forward("index"); // Same controller $this->forward("User", "profile"); // Different controller $this->forward("Admin", "User", "list"); // Different module $this->forward("index", array("key" => "value")); // With parameters } public function redirectAction() { // Redirect to URL $this->redirect("/user/profile"); } public function renderAction() { // Render template to string $html = $this->render("detail.phtml", array("id" => 123)); // Display template directly $this->display("detail.phtml", array("id" => 123)); } } ``` -------------------------------- ### Yaf Standalone Action Files Source: https://context7.com/laruence/yaf/llms.txt Demonstrates how to use Yaf_Action_Abstract to define actions in separate files from the controller. This includes mapping actions in the controller and implementing the `execute` method in the action class. ```php "actions/List.php", "detail" => "actions/Detail.php", ); public function indexAction() { $this->getView()->assign("message", "Index action in controller"); } } // Separate action class file (actions/List.php) class ListAction extends Yaf_Action_Abstract { // Required execute method public function execute() { // Access parent controller $controller = $this->getController(); $controllerName = $this->getControllerName(); // Get request data $page = $this->getRequest()->getQuery("page", 1); // Assign view variables $this->getView()->assign("items", array("item1", "item2")); $this->getView()->assign("page", $page); return true; } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.