FirstDevKit

English Deutsch

CringePHP

Version: v1.2.20 [2024-11-25]

Configuration

Please fill out the form to configure your boilerplate download. Optional fields can be enabled via checkboxes.

Note: Make sure to replace the logo, favicon, and any personal information (such as the impressum). A backlink in the impressum or elsewhere would be appreciated. Usage, distribution, and modification are free for everyone.

Documentation for CringePHP Boilerplate

Overview

The CringePHP Boilerplate deliberately avoids the classic MVC pattern and instead relies on the Structured View Pattern (SV-Pattern). This pattern, developed specifically for CringePHP, is a blend of the Template View Pattern and a minimalist application of the Front Controller Pattern. It is designed to function without additional controller and model logic, enabling quick and straightforward development.

CringePHP uses a central dispatcher that loads and displays specific views based on the URL, while helper functions provide lightweight support. This approach is ideal for smaller projects such as static pages, micropages, or single-page applications that operate without complex structures and allow for a direct, efficient workflow.

Who is this Boilerplate for?

The CringePHP Boilerplate is designed for developers seeking a fast and straightforward foundation for modern web projects. It is particularly well-suited for small to medium-sized projects where simplicity and efficiency are key – ideal for anyone looking to create a functional and high-performance website with minimal effort.

CringePHP is especially valuable for beginners and career switchers aiming to elevate their skills quickly. It provides numerous proven practices, elegant solutions, and advanced techniques that are often only discovered through extensive experience. This not only simplifies practical implementation but also fosters a deeper understanding of modern web development.

Installation and Setup

  1. Unpack: Unpack the boilerplate into the desired project directory and set /public as the webroot to ensure a secure directory structure.
  2. Plugins: Bootstrap, FontAwesome, and jQuery are pre-installed and neatly organized in the /public/plugins/ directory. This clear structure ensures better clarity, enabling a modular design.
  3. GDPR Option (beta): A GDPR option can be activated, but it must be customized individually (e.g., cookie banner, opt-in). The option is available in the /public/plugins/gdpr_v0.9.8/ folder.
  4. Contact Form and Legal Notice: Placeholder texts for the legal notice/privacy policy and a contact form are already included. These placeholder texts should be replaced with your own content.

Mechanics and Usage

  • Routing:

    • Routes are defined in the /app/routes.php file.
    • Simple and flexible URL management: URLs can be used without file extensions (e.g., .html). For example, a route /gallery can point to the file /app/views/pages/gallery.phtml.
    • Examples of routes:
    'home' => '/', // Points to /app/views/pages/home.phtml
    'item' => '/item/{id}', // usable as $this->id in the view
    'user_section' => '/user/{username}/settings/{section}', // usable as $this->username & $this->section in the view
    'my_hidden_script' => '/blume.jpg' // Loads /app/views/pages/my_hidden_script.phtml when accessing /blume.jpg (not a real image)
    • In the view, the $this->url() method can be used to generate URLs:
    $this->url('my_hidden_script'); // Returns /blume.jpg
    $this->url('item', ['id' => 12]); // Returns /item/12
    $this->url('user_section', ['username' => 'John Doe', 'section' => 'privacy']); // Returns /user/John%20Doe/settings/privacy
  • API Access:

    • API files are created in the /app/api folder and work without a defined route. Any .php file in the /app/api folder can be accessed directly via /api/[FILENAME] without additional configuration.
    • Example: The file /app/api/cart.php processes items in the cart and is directly accessible via the URL /api/cart. It automatically returns JSON responses and does not require an additional route.
  • Views:

    • View files are located in the /app/views/pages folder.
    • The file /app/views/templates/layout.phtml provides the basic structure of the page and dynamically loads individual views, allowing for a convenient and structured layout.
  • File Versioning to Prevent Caching:

    • To ensure that updated files like CSS or JavaScript are properly loaded after changes, a cache-buster is automatically applied using the asset() function.

    • Example in a view:

      <link rel="stylesheet" href="<?php echo asset('css/style.css'); ?>">
      <script src="<?php echo asset('js/core.js'); ?>"></script>
    • The parameter ?v={VALUE} is automatically appended. This value is based on the file's timestamp (Last-Modified), ensuring the browser recognizes the file as "new" when it changes.

    • This method is fully automated and ensures that file changes are correctly recognized without requiring any manual adjustments.

  • Progressive Web App (PWA):

    • CringePHP comes with built-in support to enable your website to be installed as a PWA on Android devices.
    • The "Install App" button appears at the bottom of the footer if the website has a valid HTTPS (SSL certificate). The button and its associated JavaScript are located in the layout.phtml.
    • After the installation process, the website behaves like a native app, featuring its own icon and running in a standalone window.
  • Environment Variables:

    • The framework supports `.env` files to store sensitive data such as database credentials or API keys.

    • Example of a `.env` file:

      DEBUG=true
      DB_HOST=localhost
      DB_USER=root
      DB_PASS=secret
      MAIL_HOST=smtp.example.com
    • Variables from the `.env` file can be accessed using $_ENV['VARIABLE_NAME'].

  • Error Handling:

    • The framework provides built-in error handling mechanisms:
    • In development mode (DEBUG=true):
      • All errors are displayed in the browser.
      • Uncaught exceptions are shown with stack traces.
    • In production mode (DEBUG=false):
      • All errors are logged in files within the /logs/ directory.
      • Standard log files:
        • php-error.log for general PHP errors.
        • errors.log for custom errors.
        • exceptions.log for uncaught exceptions.
  • Partials:

    • The $this->partial() method allows loading reusable template files within views.

    • Example:

      <?php echo $this->partial('navigation', ['active' => 'home']); ?>
    • Partials are located by default in the /app/views/partials directory.

  • Base URL:

    • The base_url() function returns the base URL of the website, including the protocol and domain.

    • Example:

      <?php echo base_url(); ?> // Outputs https://example.com
  • Google reCAPTCHA v3:

    • CringePHP has Google reCAPTCHA v3 already natively integrated to protect the contact form from spam and abuse.
    • The feature is ready to use as soon as the credentials (Site Key and Secret Key) are entered in the /core/config.php file.
    • Once configured, reCAPTCHA v3 protects the form automatically without requiring any additional steps.
  • 404 Page: A custom 404 error page is already set up and ready to use. For invalid URLs, the file /app/views/templates/404.phtml is automatically loaded.

  • Helper Functions:

    • Additional helper functions can be added to /app/helpers.php. These are available throughout the project and contribute to code clarity and reusability.
    • Example: A simple date formatting function could be defined in the helpers and used in a view as follows:
    // In /app/helpers.php
    function formatDate($date) {
        return date("F j, Y", strtotime($date));
    }
    
    // In a view (e.g., /app/views/pages/example.phtml)
    <?php echo formatDate("2023-01-01"); // Outputs "January 1, 2023" ?>

Lightweight Approach: No Controller, No Model

To keep the CringePHP Boilerplate slim and lightweight, it deliberately avoids using controllers and models. PHP code can be embedded directly in view files, enabling quick and straightforward implementation.

If more extensive server-side logic is required, it is recommended to use the API functionality in the /app/api directory. This approach allows for a clean separation while remaining lightweight.

Translations

  • The current language is stored in $this->lang (e.g., 'de' or 'en').
  • Translations are available for both PHP and JavaScript, allowing for easy implementation of multilingual content.
  • Supported languages can be added in the /core/config.php file, where the default language can also be set.
  • Language files are located in the /language/ directory.
<?php echo $this->translations['welcome_message']; ?>
const translations = <?php echo json_encode($this->translations); ?>;
const currentLang = '<?php echo $this->lang; ?>';
console.log(translations['welcome_message']);

Navigation with Active Link Detection

  • You can easily create a navigation bar with active link detection in CringePHP by checking the current route stored in $this->action.
  • By dynamically adding the active class, you can visually highlight the currently selected page in the navigation bar.
<nav>
    <ul>
        <li><a href="<?php echo $this->url('home'); ?>" class="<?php if ($this->action === 'home') echo 'active'; ?>"><?php echo $this->translations['home']; ?></a></li>
        <li><a href="<?php echo $this->url('about'); ?>" class="<?php if ($this->action === 'about') echo 'active'; ?>"><?php echo $this->translations['about']; ?></a></li>
        <li><a href="<?php echo $this->url('contact'); ?>" class="<?php if ($this->action === 'contact') echo 'active'; ?>"><?php echo $this->translations['contact']; ?></a></li>
    </ul>
</nav>
  • Place this code in the layout.phtml file to display the navigation consistently across all pages of the website.

Structure and Files

  • Directory Structure:
    • /public: Webroot, containing all publicly accessible files, including CSS, JavaScript, and media.
    • /app/views: Contains all view files responsible for rendering content. The views are divided into /pages (for pages), /templates (for layouts and special templates like the 404 page), and /partials (for reusable components such as navigation or headers).
    • /app/routes.php: Defines all routes for the website. Each route points to a specific view file and can include parameters.
    • /app/helpers.php: Contains project-wide helper functions that can be used across all views.
    • /core: Contains system-critical files, such as config.php for configuration and Dispatcher.php, which handles routing and view logic.
    • /language: Stores language files for multilingual content. Each language has its own file where all translations are defined.
  • Layouts and Templates: layout.phtml is located in the /app/views/templates directory and defines the basic structure of the page. It dynamically loads specific views, providing a consistent layout across the website.
  • Design and Functionality: /public/css/theme.css and /public/css/style.css as well as /public/js/core.js are organized into separate files and directories. theme.css handles theme-specific styles, while style.css contains general styling. core.js provides the functional JavaScript features.