Hongkiat https://www.hongkiat.com/blog/author/thoriq/ Tech and Design Tips Fri, 30 Aug 2024 11:53:04 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 1070734 10 FilamentPHP Plugins to Supercharge Your Laravel Admin Panel https://www.hongkiat.com/blog/filamentphp-plugins-laravel-admin-panel/ Wed, 04 Sep 2024 13:00:28 +0000 https://www.hongkiat.com/blog/?p=72707 FilamentPHP has quickly become a go-to choice for developers to build admin panels for Laravel applications. With its sleek design and powerful features, FilamentPHP provides a foundation for building anything from simple to complex panels. However, the real magic of FilamentPHP lies in the growing ecosystem of plugins that extend its functionality, allowing you to…

The post 10 FilamentPHP Plugins to Supercharge Your Laravel Admin Panel appeared first on Hongkiat.

]]>
FilamentPHP has quickly become a go-to choice for developers to build admin panels for Laravel applications. With its sleek design and powerful features, FilamentPHP provides a foundation for building anything from simple to complex panels.

However, the real magic of FilamentPHP lies in the growing ecosystem of plugins that extend its functionality, allowing you to tailor the platform to your specific needs.

In this article, we’ll explore 10 essential FilamentPHP plugins that can supercharge your admin panel, adding everything from advanced form fields to seamless integrations with third-party services or libraries. Whether you’re a seasoned FilamentPHP developer or just getting started, these plugins will help you unlock the full potential of your Laravel projects.

Here’s a quick view of what we’re featuring in the article.

Tiptap Editor A rich text editor plugin for Filament Forms.
Environment Indicator Adds a colored border to distinguish between different environments.
Spatie Media Library Allows media file management within the Filament admin panel.
ActivityLog Tracks and displays user activity logs within your application.
Table Repeater Presents form repeater items in a table layout.
Breezy A Two-Factor Authentication plugin for Filament.
Spotlight Enables quick navigation of Filament Resources with Spotlight functionality.
Fabricator A block-based page builder skeleton for Filament.
Spatie Laravel Backup Adds a page for creating backups using the Laravel Backup package.
Impersonate Allows you to authenticate and act as any user within your application.

Without further ado, let’s jump in to see the full list.

Tiptap Editor

Tiptap Editor Plugin in FilamentPHP

The Tiptap Editor is a rich text editor plugin designed specifically for Filament Forms. It integrates the Tiptap JavaScript library seamlessly into Filament Admin and Forms.

This makes it easier to add an improved text editing experience for your application.

Get Tiptap Editor

Environment Indicator

Environment Indicator Plugin in FilamentPHP

Environment Indicator is a plugin for Filament that helps you easily distinguish between different environments by adding a colored border to the top of the admin panel and a badge next to the search bar.

This way, you can see whether you’re working in development, staging, or production. It also offers customization options to allow you to change it to suit your application.

Get Environment Indicator

Spatie Media Library

Spatie Media Library Plugin in FilamentPHP

Spatie Media Library is an official Filament plugin that leverages the popular Laravel Media Library package from Spatie. It allows you to add media file management within your Filament admin panel.

This makes it easier for you to handle file uploads, associations, and storage in your applications.

Get Spatie Media Library

ActivityLog

ActivityLog Plugin in FilamentPHP

ActivityLog is a Filament plugin built on top of Spatie’s Laravel Activity Log package. It provides database relations and a timeline feature.

Additionally, it allows you to customize both the logs and how they’re displayed, giving you a clear view of your application’s logs. This plugin makes it easy to track and understand what your users are doing within your application.

Get ActivityLog

Table Repeater

Table Repeater Plugin in FilamentPHP

Table Repeater is a Filament plugin that offers a modified version of the standard Filament Forms Repeater. Instead of displaying items in a typical list format, it presents them in a table layout.

This makes it easier for you to view and manage multiple entries in a more structured manner.

Get Table Repeater

Breezy

Breezy Plugin in FilamentPHP

Breezy is a Two-Factor Authentication plugin for Filament. It provides a customizable and extendable user profile page.

Users can update their passwords, manage avatars, and handle Sanctum tokens. A perfect plugin to improve the security of your applications and provide users with easy-to-manage, self-service options.

Get Breezy

Spotlight

Spotlight Plugin in FilamentPHP

Spotlight is a handy Filament plugin that allows you to quickly navigate your Filament Resources with Spotlight functionality. It supports navigation through pages, resources, and links directly from the user menu.

This makes it easier for your users to find what they need in the application admin.

Get Spotlight

Fabricator

Fabricator Plugin in FilamentPHP

Fabricator is a block-based page builder skeleton for Filament. It handles the database and frontend routing out-of-the-box, allowing you to focus on creating layouts and page blocks.

With Fabricator, you can build custom pages efficiently, making it easier for your users to create and manage content in your Filament applications.

Get Fabricator

Spatie Laravel Backup

Spatie Laravel Backup Plugin in FilamentPHP

Spatie Laravel Backup is a Filament plugin that adds a page to your Filament admin panel, allowing you to easily create backups of your application using the spatie/laravel-backup package.

It simplifies the process of managing and securing your application’s data by providing a user-friendly interface for handling backups directly within the application.

Get Spatie Laravel Backup

Impersonate

Impersonate Plugin in FilamentPHP

Impersonate is a Filament plugin that provides a simple way to authenticate and act as any user within your application.

It gives you the ability to troubleshoot, manage, and understand user experiences from their perspective directly within the Filament admin panel.

Get Impersonate

Wrapping up

In this article, we’ve explored a range of FilamentPHP plugins, each adding unique functionality to your Filament setup.

From enhancing text editing with Tiptap Editor to managing user authentication with Breezy, these plugins can help you get the most out of FilamentPHP, whether you’re working on a simple project or managing a complex backend system.

The post 10 FilamentPHP Plugins to Supercharge Your Laravel Admin Panel appeared first on Hongkiat.

]]>
72707
Getting Started with CSS @property Rule https://www.hongkiat.com/blog/css-property-rule/ Mon, 02 Sep 2024 10:00:09 +0000 https://www.hongkiat.com/blog/?p=72701 The CSS @property is a powerful feature that brings more control and flexibility to custom properties, also known as CSS variables. It is introduced as part of the CSS Houdini project, which is designed to provide developers with deeper access to the browser’s rendering engine. The @property rule allows you to define custom properties with…

The post Getting Started with CSS @property Rule appeared first on Hongkiat.

]]>
The CSS @property is a powerful feature that brings more control and flexibility to custom properties, also known as CSS variables.

It is introduced as part of the CSS Houdini project, which is designed to provide developers with deeper access to the browser’s rendering engine. The @property rule allows you to define custom properties with specific types, default values, and even the capability to animate CSS properties.

In this article, we’ll explore what the @property rule is, why it’s useful, and how you can leverage it in your web projects.

What is @property for?

CSS custom properties, also known as CSS variables, have made styles more reusable. It allows you to define a value once and use it throughout your stylesheet.

However, one limitation has been the inability to specify a property’s type or set default values directly in CSS. This means any value can be assigned to a custom property, which can lead to unexpected results and make it harder to maintain your styles in some situations.

This is where the @property rule comes in. It allows you to set a default value, provides a fallback value that will be used if the custom property is not explicitly set, enables custom property animation, and defines a type for a custom property.

This ensures that a variable can only accept a specific data type, such as a length, color, or number.

The type of the property is defined with the syntax property. It accepts a string value defining the CSS type value, as follows:

Type Description
<length> Any valid <length> values e.g., 10px, 2em, 50%, 3rem
<number> Any valid <number> values e.g., 1, 0.5, -3, 100
<percentage> Any valid <percentage> values e.g., 50%, 100%, 25%
<length-percentage> Any valid <length-percentage> values e.g., 10px, 50%, 2em, 75%
<color> Any valid <color> values e.g., #ff0000, rgb(255, 0, 0), rgba(255, 0, 0, 0.5), blue
<image> Any valid <image> values e.g., url(image.jpg), linear-gradient(to right, red, blue)
<url> Any valid url() values e.g., url(‘https://example.com/image.jpg’)
<integer> Any valid <integer> values e.g., 1, -10, 42
<angle> Any valid <angle> values e.g., 45deg, 0.5turn, 1rad
<time> Any valid <time> values e.g., 1s, 500ms, 0.75s
<resolution> Any valid <resolution> values e.g., 300dpi, 2dppx
<transform-function> Any valid <transform-function> values e.g., rotate(45deg), scale(1.5), translateX(100px)
<custom-ident> Any valid <custom-ident> values e.g., –my-variable, custom-identifier
<transform-list> A list of valid <transform-function> values e.g., rotate(45deg) scale(1.5) translateX(100px)

Example

Let’s say we have a button component. We’d like to define some defaults on this component. Traditionally, we could use custom properties to define the background color and border radius of the button component, like so:

.button {
  background-color: #fff;
  border-radius: 8px;
}

Or, use CSS variables to define the values once and reuse them throughout the stylesheet:

:root {
  --button-bg: #fff;
  --button-rounded: 8px;
}

But, what if we want to ensure that the background color is always a valid color value, and the border radius is always a valid length value?

We can use the @property rule to define the type of these custom properties and set default values.

To do so, we could create a couple of custom properties defined with the following options in the @property rule:

@property --button-bg {
  syntax: '<color>';
  initial-value: #0D74CE;
  inherits: false;
}
@property --button-rounded {
  syntax: '<length>';
  initial-value: 8px;
  inherits: false;
}

In this example, we have two custom properties defining the background color and border radius of the button component.

We use the syntax property to define the type of the custom property, while the initial-value property sets the default value.

We also use the inherits property to specify whether the custom property inherits its value from its parent element, in which case we set them all to false to avoid inheritance.

Once they are set, we can now use these custom properties in our styles, like so:

.button {
  background-color: var(--button-bg);
  border-radius: var(--button-rounded);
}

See the Pen CSS @property by HONGKIAT (@hkdc) on CodePen.

Wrapping up

The CSS @property rule brings a significant step forward to CSS custom properties, or CSS variables. All major and latest browsers already support the CSS @property rule.

Browser Desktop Version Mobile Version
Google Chrome 85 and later 85 and later
Mozilla Firefox 128 and later Not supported
Safari 15.4 and later 15.4 and later (iOS)
Microsoft Edge 85 and later 85 and later
Opera 71 and later 71 and later
Samsung Internet 14.0 and later 14.0 and later

To sum up, the CSS @property rule is a powerful feature and a great addition to the CSS language that can help you write more maintainable and type-safe stylesheets. If you haven’t already, give it a try in your next project!

The post Getting Started with CSS @property Rule appeared first on Hongkiat.

]]>
72701
Fresh Resources for Web Designers and Developers (August 2024) https://www.hongkiat.com/blog/designers-developers-monthly-08-2024/ Fri, 30 Aug 2024 13:00:30 +0000 https://www.hongkiat.com/blog/?p=72693 August 2024 brings us a collection of new tools, libraries, and resources to help you build better websites and applications, and improve your productivity as designers and developers. We’ve got everything from design inspiration to development tools, and everything in between. Let’s explore and see what’s new this month. e18e e18e is a community-driven initiative…

The post Fresh Resources for Web Designers and Developers (August 2024) appeared first on Hongkiat.

]]>
August 2024 brings us a collection of new tools, libraries, and resources to help you build better websites and applications, and improve your productivity as designers and developers. We’ve got everything from design inspiration to development tools, and everything in between.

Let’s explore and see what’s new this month.

e18e

e18e is a community-driven initiative focused on improving the JavaScript ecosystem. It aims to bring together people who are passionate about JavaScript by sharing knowledge, contributing ideas, and collaborating.

It has three key areas of focus: cleaning up and modernizing dependency trees, speeding up core packages and frameworks, and offering modern, lighter alternatives to core packages.

e18e JavaScript ecosystem community initiative

FreeFaces Gallery

FreeFaces Gallery is a curated collection of fonts available under various free licenses. It provides a range of typefaces, including Cursive, Display, Monospace, Sans Serif, Serif, and Slab.

It’s a valuable resource if you’re searching for high quality free fonts.

FreeFaces Gallery font collection

AppMotion Design

AppMotion is a mobile motion design gallery that showcases the best, hand-picked examples of app motion design. The gallery allows you to explore various design elements, such as checkboxes, pinch, spin, morph, and more.

A useful resource if you’re looking for inspiration in mobile app animations.

AppMotion mobile motion design gallery

LogoIpsum

LogoIpsum is a tool that provides a collection of abstract, flexible SVG logos in various compositions—vertical, horizontal, small, and large. These logos are suitable for any graphic, UI, or layout style.

It’s a perfect resource for designers needing temporary placeholder logos before the final design is ready.

LogoIpsum SVG logo collection

ShaderGradient

ShaderGradient is a tool for creating dynamic, moving gradients that can be customized for various designs. It’s available as a React component and can be used in design tools like Figma and Framer.

A handy tool to bring your designs to life with vibrant gradients.

ShaderGradient moving gradients tool

Shots

Shots.so is a free online tool that helps you create beautiful mockups quickly. Simply upload your screenshot, select from scenes with the latest Apple devices, and customize the details.

It also offers browser, laptop, and mobile scenes to highlight your work.

Shots.so mockup creation tool

SneakPeekit

SneakPeekit provides printable wireframe templates for designers to sketch ideas and capture insights on paper. It offers various sizes for both desktop and mobile.

If you prefer planning apps or websites with pencil and paper, these templates help speed up the creative process.

SneakPeekit wireframe templates

SVGMagic

SVGMagic is an open-source package for Next.js projects that simplifies the use of SVGs. It supports both SVG code and .svg files with seamless integration with TypeScript and MDX.

It makes it easy to deliver your creativity in SVG while also improving your development workflow.

SVGMagic SVG management package

Giscus

Giscus is an open-source comment system for websites that uses GitHub Discussions for storing comments and reactions. It offers privacy with no tracking or ads and will always be free.

It also supports custom themes, multiple languages, and automatic updates from GitHub. It is a flexible and secure choice if you’re looking to add a comment system to your site.

Giscus GitHub-based comment system

Orbit

Orbit is a GitHub Action specifically designed for a Laravel development environment, enabling simple and safe zero-downtime deployments. It offers an easy way to configure your deployment process through a special file, Orbit.toml.

This allows you to deploy your Laravel sites to your server quickly while ensuring that your site remains live throughout the process.

Orbit Laravel zero-downtime deployment

Glaze

Glaze is a utility-based animation library for the web, built on top of GSAP. It provides a powerful way to create complex animations with minimal code using a utility-first approach like TailwindCSS.

It supports responsive design and allows you to easily define animations for different screen sizes. A handy tool for adding dynamic animations to your web projects.

Glaze GSAP-based animation library

Motion Number

MotionNumber is a React.js component built on top of Framer Motion, designed to smoothly transition, format, and localize numbers.

It’s a handy library to create dynamic and visually appealing number animations in your projects.

MotionNumber React.js number animation component

Zen Browser

Zen is a new browser built on Firefox’s engine. It aims to provide a fast, secure, and privacy-focused web browsing experience.

This browser is designed to ensure your data remains private and secure. A good choice if you’re looking for an alternative browser that respects your privacy.

Zen privacy-focused web browser

Ky

Ky is a lightweight library for modern environments. It aims at improving the native fetch API with a simpler interface, method shortcuts, error handling, retries, and JSON support.

It also offers customization through instances and hooks and includes TypeScript support for better type safety. It’s a great alternative for handling HTTP requests in your projects.

Ky lightweight fetch API library

TailwindCSS Course

This free YouTube course by Chris Sev will help you learn TailwindCSS. Alongside learning Tailwind, it also covers essential CSS concepts.

This course is a comprehensive guide if you’re looking to both master TailwindCSS and understand the fundamentals of design with CSS.

TailwindCSS YouTube course by Chris Sev

Pines

Pines is a UI library designed for Alpine and Tailwind projects. It provides a collection of ready-to-use animations, and components like sliders, tooltips, accordions, modals, and more.

It also allows you to easily copy and paste these elements into your projects. A convenient resource if you want to quickly add interactive elements to your site.

Pines UI library for Alpine and Tailwind

PHP CSS Parser

PHP-CSS-Parser is a PHP library that parses CSS files, allowing you to extract them into a data structure. It allows you to manipulate the CSS and then output it as optimized CSS.

A very useful library if you need to work with and modify CSS programmatically in your PHP application.

PHP-CSS-Parser PHP library for CSS

Noodle

Noodle is an open-source app created to help students stay organized with their studies. It is designed to provide a single platform that meets all the needs of students, much like GitHub does for developers.

At the time of this writing, Noodle is currently in development, but you can follow the project on GitHub to stay updated on its progress.

Noodle open-source student organization app

Omi

Omi is a web components framework. It provides a wide range of features with over 100 templates, form components, and icon sets, with support for both object-oriented and data-oriented programming.

It is written in JSX, integrates seamlessly with modern tools like TailwindCSS, and provides everything you need for building web applications, including routing and styling through Constructable Stylesheets.

Omi web components framework

The post Fresh Resources for Web Designers and Developers (August 2024) appeared first on Hongkiat.

]]>
72693
Laravel Development Environment Compared https://www.hongkiat.com/blog/laravel-development-environment-comparison/ Thu, 15 Aug 2024 13:00:04 +0000 https://www.hongkiat.com/blog/?p=72551 When developing a Laravel application, having a reliable local development environment is as important as the code itself. A good local development environment can help you work more efficiently, test your code, and avoid potential deployment issues. There are several tools available within the Laravel ecosystem, such as Homestead, Valet, Sail, and Herd, as well…

The post Laravel Development Environment Compared appeared first on Hongkiat.

]]>
When developing a Laravel application, having a reliable local development environment is as important as the code itself. A good local development environment can help you work more efficiently, test your code, and avoid potential deployment issues.

There are several tools available within the Laravel ecosystem, such as Homestead, Valet, Sail, and Herd, as well as tools outside their ecosystem like MAMP.

Laravel Development Environment

Each tool offers unique features and benefits, catering to different needs and workflows. In this article, we’ll compare these tools to help you choose the best one for your local Laravel development.

Homestead

Laravel Homestead development environment screenshot

Laravel Homestead is an official Vagrant box that provides a ready-to-use development environment with PHP, Nginx, MySQL, and Redis pre-installed.

Homestead runs on a virtual machine, ensuring that your development setup is consistent, no matter where you work, and does not affect configurations or other applications on your machine. Homestead also supports multiple PHP versions, making it easy to switch between them. You can configure and manage your setup using a simple Homestead.yaml file.

Homestead is a great option for developers working on projects that require a full-featured virtual machine. Otherwise, lighter options might be preferable.

Pros
  • Provides a full-featured development environment out of the box
  • Isolated environment prevents conflicts with other local software
  • Supports multiple sites and projects
Cons
  • Requires Vagrant and VirtualBox, which can be resource-intensive
  • Setup can be more complex compared to other tools

Valet

Laravel Valet setup on macOS

Laravel Valet is a lightweight development environment designed for macOS users. It automatically sets up your Mac to run Nginx in the background and uses DnsMasq to route requests on the *.test domain to your local sites.

Though it is not intended as a replacement for more robust environments like Homestead, it offers a quick, flexible setup. It also supports a variety of other frameworks and CMSs, such as WordPress, Symfony, and Drupal, straight out of the box.

It is perfect for macOS users who prefer a fast and lightweight setup with minimal configuration.

Pros
  • Lightweight and fast, with minimal resource usage
  • Supports multiple PHP versions
  • Seamless integration with other tools like Ngrok and Expose to share your local sites
Cons
  • Limited to macOS
  • Apache is not supported
  • Less isolation compared to virtualized environments, which may cause conflicts with other software on your machine

Sail

Laravel Sail Docker environment setup

Laravel Sail is a Docker-based development environment that provides a simple command-line interface for interacting with Docker.

It comes with pre-configured services like MySQL, Redis, MeiliSearch, and more, making it easy to get started with Laravel projects. Since it is based on Docker, you can easily configure your environment or add any other services that you may need but are not included by default through the compose.yml file.

It is best for developers who prefer Docker-based workflows and want an easily configurable environment.

Pros
  • Consistent development environment across different platforms: Windows, macOS, and Linux
  • Fast and simple CLI to start and stop projects
  • Easily customizable
Cons
  • Requires Docker, which can be complex for beginners
  • Requires WSL to run on Windows
  • Performance can be an issue on some systems

Herd

Laravel Herd desktop app interface

Laravel Herd is a desktop app designed to create a fast, lightweight, and user-friendly local development environment for Laravel applications. It offers a simple, zero-configuration setup and includes everything you need to get started, such as Composer, the Laravel installer, a debugger, and essential services like MySQL.

Additionally, Herd provides a seamless migration tool from Laravel Valet, and it allows you to manage different versions of Node.js and PHP. You can also manage SSL certificates and other services easily through its user-friendly interface.

A great application if you prefer ease of use with a nice UI.

Pros
  • Comes as a desktop app with a user-friendly interface
  • Lightning-fast since it directly includes the PHP and Composer binaries
  • Node.js and SSL management
Cons
  • Limited to macOS
  • Full features only available in the paid version

MAMP

MAMP interface on macOS

MAMP is a popular tool for creating a local server environment on macOS and Windows. While it’s not specifically designed for Laravel, you can configure MAMP to run Laravel applications.

It provides an easy way to set up PHP, MySQL, and Apache or Nginx, as well as other tools on your local machine. It also includes features like PHP version switching and a user-friendly interface. This makes it a convenient option for developers who want to work on Laravel projects and other PHP projects without needing to install and configure everything manually.

Suitable for those who need a cross-platform solution and work with various PHP applications outside Laravel.

Pros
  • Simple and user-friendly interface
  • Suitable for various PHP applications, not just Laravel
  • Supports both Apache and Nginx
Cons
  • Less tailored to Laravel-specific needs, so manual configuration might still be required in some cases

Conclusion

Choosing the right tool for running Laravel on localhost depends on your development needs, preferences, and operating system. Consider your specific requirements and workflow to choose the best option for your Laravel development.

The post Laravel Development Environment Compared appeared first on Hongkiat.

]]>
72551
Native CSS Masonry Grid https://www.hongkiat.com/blog/native-css-masonry-grid/ Thu, 08 Aug 2024 13:00:50 +0000 https://www.hongkiat.com/blog/?p=72518 One popular layout style on the web is the masonry layout, often used in image galleries and portfolio websites to display images or items of varying sizes. Traditionally, creating a masonry layout required JavaScript libraries, such as the popular Masonry.js by DeSandro and MiniMasonry. However, with CSS Grid, you can now create this layout using…

The post Native CSS Masonry Grid appeared first on Hongkiat.

]]>
One popular layout style on the web is the masonry layout, often used in image galleries and portfolio websites to display images or items of varying sizes.

Traditionally, creating a masonry layout required JavaScript libraries, such as the popular Masonry.js by DeSandro and MiniMasonry. However, with CSS Grid, you can now create this layout using pure CSS.

In this article, we will explore what a CSS Grid masonry layout is and provide some examples to help you understand how it works. Let’s get started.

Getting Started

CSS Grid is a native CSS layout system that provides a grid-based framework where you can define rows and columns and place items within this grid. The masonry layout can be created by combining CSS Grid with certain properties that allow items to span multiple rows or columns, creating the masonry effect. Let’s start with a simple example to understand the basics of creating a masonry layout using CSS Grid.

First, we have the HTML. We have a container with eight items. Each item has a different height and width so that we can see the masonry effect more clearly.

<div class="masonry">
    <div class="gallery">
        <figure>
            <img src="images/image-1.jpg" width="600" height="1200" />
        </figure>
    </div>
    <div class="gallery">
        <figure>
            <img src="images/image-2.jpg" width="400" height="200" />
        </figure>
    </div>
    // 6 more items...
</div>

And, the CSS, as follows:

.masonry {
    display: grid;
    grid-template-columns: repeat(6, 1fr);
    grid-template-rows: masonry;
    gap: 10px;
}
// More stylistic styles...

The grid-template-columns property defines six equal columns, the gap property adds space between the grid items, and the grid-template-rows: masonry; property creates the masonry layout based on the available space within the grid container.

Default masonry layout

You can adjust the layout behavior using the masonry-auto-flow property. When set to next, this property displays items in order along the grid axis instead of placing them in the track with the most free space. As shown below, the items are placed in order from left to right, top to bottom, regardless of the available space.

Masonry layout with next auto-flow

Making It Responsive

One of the advantages of using CSS Grid is that it allows you to create responsive layouts with ease. You can use media queries to adjust the grid layout based on the screen size. For example, you can change the number of columns in the grid based on the screen width to ensure that the layout looks good on different devices.

@media (max-width: 1200px) {
    .masonry {
        grid-template-columns: repeat(4, 1fr);
    }
}
@media (max-width: 640px) {
    .masonry {
        grid-template-columns: repeat(2, 1fr);
    }
}

You can also change the repeat() value to use auto-fill and minmax() functions to create a responsive layout that automatically adjusts the number of columns based on the available space. The minmax() function allows you to set a minimum and maximum size for the columns, ensuring that they don’t get too small or too large.

.masonry {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    grid-template-rows: masonry;
    gap: 10px;
}

That’s it! You now have a responsive masonry layout that adjusts based on the screen size. You can experiment with different values for the minmax() function and the gap property to achieve the desired layout for your project.

Browser Support

It’s important to note that CSS Grid with the masonry layout is still in the experimental stage and not yet supported in mainstream browsers.

Browser Version Support
Google Chrome Not supported
Firefox 77-131 Experimental. Can be enabled from config.
Safari Technology Preview Supported
Microsoft Edge Not supported
Opera Not supported
Safari on iOS Technology Preview Supported
Android WebView Not supported
Samsung Internet Not supported

As shown in the table, you can view the masonry layout in the Safari Technology Preview or Firefox.

If you’re using Firefox, type about:config in the address bar, search for the configuration name, and set it to true. The update will take effect immediately, so you can refresh the page without needing to restart the browser.

Firefox about config screen

The status of browser support may change, so it’s a good idea to check the latest updates from the respective browser documentation or support pages.

Wrapping Up

The CSS Grid masonry layout is a powerful tool that allows you to create complex grid-based layouts with ease. By combining CSS Grid with media queries and other CSS properties, you can create responsive masonry layouts that look great on all devices. While the masonry layout is still in the experimental stage, it is worth experimenting with to see how it can benefit your projects.

Last but not least, here’s a CodePen demo for you to try out. Enjoy!

See the Pen CSS Grid Masonry by HONGKIAT (@hkdc) on CodePen.

The post Native CSS Masonry Grid appeared first on Hongkiat.

]]>
72518
CSS Container Queries https://www.hongkiat.com/blog/css-container-queries/ Wed, 31 Jul 2024 13:00:15 +0000 https://www.hongkiat.com/blog/?p=72453 In traditional responsive design, we rely on media queries to change styles based on the overall viewport size. This works well for adjusting layouts for different screen sizes, but it falls short when you need components to adapt based on their container’s size. To solve this situation, Container Queries were introduced in CSS. They allow…

The post CSS Container Queries appeared first on Hongkiat.

]]>
In traditional responsive design, we rely on media queries to change styles based on the overall viewport size. This works well for adjusting layouts for different screen sizes, but it falls short when you need components to adapt based on their container’s size.

To solve this situation, Container Queries were introduced in CSS. They allow you to apply styles to elements based on the dimensions of their containing block, giving you more granular control over responsive design.

Let’s say we have a Card component, containing an image, title, and a few paragraphs. The Card has two layout modes: horizontal for large screens and vertical for smaller screens.

In the horizontal mode, the image will be on the left, and the title and paragraphs are on the right.

Card horizontal layout
Card in horizontal layout

In the vertical mode, the image is on top, and the title and paragraphs are below it.

Card vertical layout
Card in vertical layout

We want this Card to switch between these two modes. Traditionally, we would wrap the styles around the @media query, for example:

.card {
    display: flex;
    gap: 4rem;
}
.card .featured-img {
    width: 40%;  
}
.card .content {
    width: 60%;  
}

@media screen and (width <= 720px) {
    .card {
      flex-direction: column;
    }
    
    .card .featured-img {
      width: 100%;  
    }
  
    .card .content {
      width: 100%;  
    }
}

The problem here is that Media Queries only account for the viewport size, not the container size. If the Card is placed inside a container with a width of 500px, the Card will still be in the horizontal mode, even though it's not suitable for the container size. We may end up with the content and the image being squished, or the image overflowing the container.

Card with media query

This is one example where Container Queries can be useful. With Container Queries, we can apply styles based on the container's size, instead of just the viewport size.

To use them, we will need to wrap our .card with a new container. In this example, we will name it .card-container. Then we can add it with the container-type: inline-size declaration.

.card-container {
    container-type: inline-size;
    width: 100%;
}

The inline-size value specifically enables querying the inline dimension, usually the width in horizontal writing modes of a container.

When we set container-type: inline-size on an element, we're essentially telling the browser to treat that element as a container whose width can be queried using Container Queries. This is required for applying styles based on the size of the container, rather than the viewport. The width is also important to ensure the container takes up the full width of its parent.

Now, we can apply the styles based on the container's size in addition to the Media Queries:

@container (max-width: 720px) {
    .card {
        flex-direction: column;
    }
    
    .card .featured-img {
        width: 100%;  
    }
    
    .card .content {
        width: 100%;  
    }
}

The two cards from our example should now switch to the vertical layout when the container's width is less than 720px, regardless of the current viewport size.

Card with container query

Browser Compatibility

Browser Desktop Version Mobile Version
Google Chrome 105 and later 105 and later
Mozilla Firefox 109 and later 109 and later
Safari 16.4 and later 16.4 and later
Microsoft Edge 105 and later 105 and later
Opera 91 and later 91 and later
Internet Explorer Not supported Not supported
Samsung Internet N/A 20.0 and later

Inspirations

We've walked through a very common use case of using Container Queries. We can actually do so much more with them to create more innovative features on our website, such as combining them with animations, interactive elements, and more. Here are some demos of using Container Queries for your inspiration.

CSS Container Query House

You can resize the container size vertically or horizontally and see the house expand with more rooms and windows.

See the Pen CSS Container Query House by Arco (@Lumocra) on CodePen.

See the Pen Responsive House with CSS Container Query by Gayane Gasparyan (@gayane-gasparyan) on CodePen.

Squish CSS Container Queries

Click the button Add Squishy to add more squishies inside the block and see how their reaction changes the more you add as there isn't enough room inside.

See the Pen CSS Container Queries by Max Swann (@maxcswann) on CodePen.

The post CSS Container Queries appeared first on Hongkiat.

]]>
72453
Snappy Scroll with CSS Scroll Snap https://www.hongkiat.com/blog/css-scroll-snap/ Wed, 31 Jul 2024 10:00:40 +0000 https://www.hongkiat.com/blog/?p=72433 CSS Scroll Snap was introduced to allow you to define snap points for scrollable elements. It ensures that the scrolling lands precisely at the desired points. This new CSS feature is especially useful for creating carousels, slideshows, or any layout where you want to control the user’s scrolling experience. Let’s see how it works. New…

The post Snappy Scroll with CSS Scroll Snap appeared first on Hongkiat.

]]>
CSS Scroll Snap was introduced to allow you to define snap points for scrollable elements. It ensures that the scrolling lands precisely at the desired points.

This new CSS feature is especially useful for creating carousels, slideshows, or any layout where you want to control the user’s scrolling experience. Let’s see how it works.

New Properties

The CSS Scroll Snap module introduces two main new properties to give us more control of the scrolling behavior:

  • scroll-snap-type: This property is applied to the container element to define the snapping behavior. It can be set to x, y, or both to specify the axis of snapping. It also takes a second argument which can be set to mandatory or proximity. The mandatory value forces the scroll to snap to the nearest snap point, while proximity allows the scroll to stop at any point within the snap area.
  • scroll-snap-align: This property is applied to the scrollable elements within the container to define the snap points. It can be set to start, center, or end to specify where the element should snap to the container. It can also be set to none to disable snapping for a specific element.

Creating Carousel

First, let’s say we want to create a horizontal carousel of images. We want each image to slide and immediately snap into place as we scroll it. First, we place the HTML, as follows:

<div class="carousel">
    <div class="slide">
        <img src="/image-1.jpg" width="600" height="400" />
    </div>
    <div class="slide">
        <img src="/image-2.jpg" width="600" height="400" />
    </div>
    <div class="slide">
        <img src="/image-3.jpg" width="600" height="400" />
    </div>
    <div class="slide">
        <img src="/image-4.jpg" width="600" height="400" />
    </div>
</div>

As well as the styles.

.carousel {
    display: flex;
    overflow-x: scroll;
    scroll-snap-type: x mandatory;
}

.image {
    flex: 0 0 100%;
    scroll-snap-align: center;
    
    /* Stylistic elements */
    width: 100%;
    height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 2rem;
    background-color: #dddddd;
}

In this example, we set the scroll-snap-type property to x mandatory on the .carousel container, indicating that the scroll snapping should happen horizontally and be mandatory. We also set the scroll-snap-align property to center on the .image elements, meaning each image will snap to the center of the container as you scroll.

See the Pen Scroll Snap by HONGKIAT (@hkdc)on CodePen.

To make it scroll vertically, we can simply set the scroll-snap-type value to y, and change the direction of our Flex layout so each element would stack vertically.

.carousel {
    display: flex;
    flex-direction: column;
    overflow-y: scroll;
    height: 100vh;
    scroll-snap-type: y mandatory;
}

/* ...Remaining code... */

Now, let’s scroll vertically.

See the Pen Scroll Snap (Vertical) by HONGKIAT (@hkdc) on CodePen.

Browser Support

Browser Desktop Version Mobile Version
Google Chrome 69 and later 127 and later
Mozilla Firefox 68 and later 68 and later
Safari 11 and later 11 and later
Microsoft Edge 79 and later 79 and later
Opera 64 and later 80 and later
Internet Explorer Not supported Not supported
Samsung Internet N/A 10.1 and later

Wrapping up

CSS Scroll Snap is a powerful tool for creating smooth and controlled scrolling experiences. Whether you’re building a carousel, a slideshow, or any scrollable layout, you can now create the perfect scrolling effect without any JavaScript added.

In this article, we’ve only touched the very basic implementations. There are a lot more creative ways we can leverage CSS Scroll Snap. Here are some of them for your inspiration.

CSS-only Carousel

Our carousel created in this article is pretty basic. The following demo shows how you can add controls like buttons and pagination into the carousel, all without any JavaScript involved.

See the Pen A CSS-only Carousel Slider by Christian Schaefer (@Schepp)on CodePen.

Animated Verbs

Similar to what we created here, but with more vibrant colors, added with animated text.

See the Pen Animated Verbs by Ryan Mulligan (@hexagoncircle)on CodePen.

Digital Walls

Creative use of grid layouts combined with CSS Scroll Snap on each column.

See the Pen Modern Blog Layout with CSS Grid by Aysenur Turk (@TurkAysenur) on CodePen.

The post Snappy Scroll with CSS Scroll Snap appeared first on Hongkiat.

]]>
72433
:where() – CSS: Cascading Style Sheets https://www.hongkiat.com/blog/where-css-selector/ Mon, 29 Jul 2024 10:00:24 +0000 https://www.hongkiat.com/blog/?p=72388 Managing CSS can be tricky, especially when styles need to override each other. This often makes it hard to keep the styles in the right places. To simplify things, the :where selector was added in CSS. This is a special CSS selector that allows you to group selectors without increasing their specificity, making it easier…

The post :where() – CSS: Cascading Style Sheets appeared first on Hongkiat.

]]>
Managing CSS can be tricky, especially when styles need to override each other. This often makes it hard to keep the styles in the right places. To simplify things, the :where selector was added in CSS. This is a special CSS selector that allows you to group selectors without increasing their specificity, making it easier to override styles when needed.

Consider the following HTML:

    

1st paragraph

    
      

2nd paragraph

    
    

3rd paragraph

    

4th paragraph

    

5th paragraph

We have two div elements. One is inside #root, and the other is outside of it. We want paragraphs inside #root to be red and paragraphs inside .section to be green. Typically, you can write CSS as follows:

#root p {
    color: red;
}
.section p {
    color: green;
}

However, with this CSS, the paragraph inside .section will be green, but the paragraphs inside #root will remain red instead of turning green. This happens because the specificity of the #root selector is higher than that of the .section selector.

See the Pen CSS :where selector by HONGKIAT (@hkdc) on CodePen.

To solve this situation, traditionally, we could update our CSS as follows:

#root p {
    color: red;
}
.section p,
#root .section p {
    color: green;
}

But this is not ideal because it increases the specificity of the selector and makes them look more complex. It will eventually cause more problems when we need to override the styles.

This is where the :where selector comes in. With the :where selector, you can group selectors without increasing their specificity. Here’s how we can update our CSS instead:

:where(#root) p {
    color: red;
}
.section p {
    color: green;
}

The #root selector is wrapped with the :where selector, which will reduce its specificity to 0. This will allow the paragraph inside .section to be all green, even though it is inside #root.

See the Pen CSS :where selector (before) by HONGKIAT (@hkdc) on CodePen.

How is it different from the :is selector?

The :where selector is similar to the :is selector, where we can group a number of selectors together. The main difference is their behavior affecting the specificity within the group. While the :where selector will remove it (or set it to 0), the :is selector may increase the specificity of the selector with the highest specificity within the group.

Let’s take a look at the following example:

.section p {
    color: green;
}

.section .highlight {
    color: orange;
}

p:first-of-type {
    color: red;
}

The result would be that only the first and third paragraphs would turn red. The second paragraph would remain orange since .section .highlight has higher specificity than the p:first-of-type, even though it is also the first paragraph.

See the Pen CSS :where vs :is selector by HONGKIAT (@hkdc) on CodePen.

Traditionally, we can always rewrite our CSS, as follows:

p:first-of-type,
.section p:first-of-type {
    color: red;
}

Alternatively, we can also write it this way:

p:first-of-type,
p.highlight:first-of-type {
    color: red;
}

However, this again results in more complex selectors and complicated specificity issues down the road. With the :is selector, we can have it much simpler to solve this issue with the following rules.

:is(div, section, .section) p:first-of-type {
    color: red;
}

We group together div, section, and .section. This group will have the same specificity as .section so the color red will apply to both within the div and the section elements as well.

See the Pen CSS :where vs :is selector (applied) by HONGKIAT (@hkdc) on CodePen.

Browser Compatibility

Browser Desktop Version Desktop Support Mobile Version Mobile Support
Google Chrome 88 and later Supported 88 and later Supported
Mozilla Firefox 78 and later Supported 78 and later Supported
Safari 14.1 and later Supported 14.5 and later (iOS) Supported
Microsoft Edge 88 and later Supported 88 and later Supported
Opera 75 and later Supported 61 and later Supported
Internet Explorer Not supported Not supported Not supported Not supported
Samsung Internet N/A N/A 14.0 and later Supported

Wrapping up

The :where selector is a great addition to CSS that allows you to group selectors without increasing their specificity. This makes it a perfect selector to add base styles to a group of elements without worrying about the specificity of the selector. It overall makes it easier to manage styles without complicating specificity and override them when needed.

Bonus: Check out Specificity Calculator to see how the specificity of your CSS selectors is calculated.

The post :where() – CSS: Cascading Style Sheets appeared first on Hongkiat.

]]>
72388
A Look Into: CSS “:is” Selector https://www.hongkiat.com/blog/css-is-selector/ Fri, 26 Jul 2024 10:00:08 +0000 https://www.hongkiat.com/blog/?p=72377 The CSS :is selector is a handy pseudo-selector that simplifies complex selector queries. It allows you to group multiple selectors into a single, more readable form, which can help reduce redundancy and make your CSS more maintainable. Before the :is selector, you’d need to repeat the same styles for multiple selectors, leading to long and…

The post A Look Into: CSS “:is” Selector appeared first on Hongkiat.

]]>
The CSS :is selector is a handy pseudo-selector that simplifies complex selector queries. It allows you to group multiple selectors into a single, more readable form, which can help reduce redundancy and make your CSS more maintainable.

Before the :is selector, you’d need to repeat the same styles for multiple selectors, leading to long and repetitive code. For example, if you wanted to apply the same styles under the main element to the a and the button elements, you would write:

main a,
main button {
  color: blue;
}

With the :is selector, you can group the selectors into a single line:

main :is(a, button) {
  color: blue;
}

You can also combine it with other pseudo-selector, for example, the :hover, which in this example we will make the color to orange.

main :is(a, button):hover {
  color: orange;
}

As you can see, the :is selector simplifies the code and makes it easier to read. It’s especially useful when you have a long list of selectors that share the same styles.

Specificity

One important thing to note about the :is selector is that it doesn’t affect the specificity of the selector. The specificity of the :is selector is the same as the most specific selector within the group. For example, in the following code:

main :is(a, button) {
  color: green;
}

main a,
main button {
  color: red;
}

The specificity of the :is(a, button) selector is the same as the a selector, which means that if there are conflicting styles, which ever style is defined last will be applied. In this case, we are going to see the color of the button and the anchor will turn red.

See the Pen CSS :is selector by HONGKIAT (@hkdc) on CodePen.

But keep in mind that if there’s a more specific selector within the group, the specificity of the :is selector will be the same as that selector. For example, in the following code…

main :is(a, .btn) {
  color: green;
}

main a,
main button {
  color: red;
}  

…we have class selector, .button, to select the button element so the specificity of the :is(a, .btn) selector is the same as the .btn selector, which means that the color of both the button and the link will turn green.

See the Pen CSS :is selector by HONGKIAT (@hkdc) on CodePen.

Conclusion

The :is selector simplifies complex selector queries. It allows you to group multiple selectors into a single, more readable form, which can help reduce redundancy and make your code easier to read. However, keep in mind the specificity of the :is selector is the same as the most specific selector within the group, so be careful when using it in your stylesheets.

Browser Compatibility

Browser Desktop Version Desktop Support Mobile Version Mobile Support
Google Chrome 88 and later Supported 88 and later Supported
Mozilla Firefox 78 and later Supported 78 and later Supported
Safari 14.1 and later Supported 14.5 and later (iOS) Supported
Microsoft Edge 88 and later Supported N/A N/A
Opera 75 and later Supported 61 and later Supported
Internet Explorer Not supported Not supported N/A N/A
Samsung Internet N/A N/A 14.0 and later Supported

The post A Look Into: CSS “:is” Selector appeared first on Hongkiat.

]]>
72377
Fresh Resources for Web Designers and Developers (July 2024) https://www.hongkiat.com/blog/designers-developers-monthly-07-2024/ Wed, 24 Jul 2024 13:00:28 +0000 https://www.hongkiat.com/blog/?p=72379 July is here, and we are back with a fresh set of resources for our fellow web developers. This month, we have a variety of tools and libraries covering different areas of web development, from libraries, frameworks, guides, and best practices, to inspiration. Without further ado, let’s jump in and see the full list. Autofix…

The post Fresh Resources for Web Designers and Developers (July 2024) appeared first on Hongkiat.

]]>
July is here, and we are back with a fresh set of resources for our fellow web developers. This month, we have a variety of tools and libraries covering different areas of web development, from libraries, frameworks, guides, and best practices, to inspiration. Without further ado, let’s jump in and see the full list.

Autofix CI

Autofix.ci is a tool for GitHub Action that automatically fixes your pull requests. You can define a GitHub Action workflow, run your code-fixing tools, and it will update your pull requests as needed. It works with existing linters, formatters like Prettier and ESLint, and other tools without extra configuration. It supports all pull requests, including those from forks and unprotected branches.

Autofix CI logo

Composer Unused

composer-unused is a tool that scans your code to show unused Composer dependencies. Unlike the composer why command, which only shows why a package is installed, composer-unused checks if the symbols provided by a package are used in your code.

Composer Unused tool

ESLint Config Inspector

ESLint Config Inspector is a visual tool for understanding and inspecting the ESLint flat configuration file, introduced in ESLint v9.0.0. Managing config files is easy but can still be complex as it grows. This tool helps you see which rules are enabled or disabled, making it simpler to understand and manage your ESLint setup.

ESLint Config Inspector

MySQL Explain

MySQL Explain is a web app that visualizes the MySQL EXPLAIN output. Instead of struggling with MySQL’s cryptic output, you can use this tool to quickly identify performance problems, helping you to avoid slow or costly database queries.

MySQL Explain app

Harlequin

Harlequin is a powerful and colorful database client run from the Terminal. It works on any shell environment, terminal, or machine, and supports various databases, including MySQL and Postgres. It features a data catalog to view tables and columns, a query editor with autocomplete and multiple tabs, and a results viewer that can handle over a million results interactively.

Harlequin database client

Write Description Text

An extensive guide on writing alt text. It covers the very basics and principles of text descriptions, and provides instructions for both decorative images, which are included for aesthetic purposes, and informative images, which communicate information, convey mood, or enhance user experience.

Even though the guide is designed to be used in BBC News articles, there are many things we can learn and apply to our own websites.

Guide on writing alt text

Shipping Incrementally

If you work in the tech industry, you might be familiar with the pressure to build and ship products quickly, often leading to rushed, stressful, and risky releases. This article, by Zahra Traboulsi, advocates for the shipping incrementally approach. It requires conscious effort to adopt but ultimately makes daily tasks easier and reduces the stress associated with project deadlines. It’s well worth the read for anyone working in tech.

Shipping Incrementally article

Once: Writebook

Writebook is a user-friendly tool that allows you to instantly publish your own books on the web for free, without needing a publisher. It makes it easy to turn your text and pictures into a simple, browsable online book format. It makes the publishing process easier compared to traditional blogging and social media posting.

Writebook publishing tool

Animotion

Animotion is a library that allows you to create animated presentations easily using Svelte, Reveal.js, and Tailwind CSS. It uses SvelteKit as the template, making it simple to deploy your presentations with the SvelteKit adapters, including Cloudflare Pages, Netlify, Vercel, and more.

Animotion library

Vue.js Crash Course 2024

The Vue.js Crash Course 2024 is a 3-hour YouTube tutorial by Traversy Media. It covers the basics of the Vue.js framework. You’ll learn about components, directives, lifecycle, events, and other essential topics. A great resource for mastering Vue.js fundamentals, whether you’re just getting started or looking for a refresher.

Vue.js Crash Course tutorial

Wire in the Wild

Wire in the Wild is a website showcasing real-world projects built with Laravel Livewire or the TALL Stack. It provides inspiration and demonstrates the possibilities of Livewire. You can submit your own projects, making it a valuable resource for both developers and clients.

Wire in the Wild site

Minji

Minji is a free iPhone app that helps you manage projects and clients easily. With a simple, intuitive interface, you can create, organize, and track tasks, filter projects by status, and manage clients. A perfect app for freelancers, team leads, and project managers looking to be more productive.

Minji app interface

dotUI

dotUI provides a collection of modern, mobile-friendly UI components built on top of React Aria Components. It’s designed to help you create an accessible React application and user-friendly interface with ease.

dotUI logo

Lume

Lume is a static site generator for Deno. It’s designed to be easy to use, while also offering flexibility and support for various file formats like Markdown, YAML, and JavaScript. It simplifies your workflow by avoiding the hassle of managing many packages and complex bundlers.

Lume static site generator

Laravel Error Solutions

laravel-error-solutions is a Laravel package that enhances error pages by displaying helpful solutions directly on them. It provides automatic fix buttons for common issues and also supports AI-generated solutions. It helps you resolve problems in your Laravel application more efficiently.

Laravel Error Solutions

SSH Action

SSH Action allows you to run remote SSH commands as part of your CI/CD workflows. It’s useful for automating tasks on remote servers, such as deploying code, running scripts, or managing server configurations, all directly from your GitHub repository. It can help you streamline your app or website deployment process and operations.

SSH Action tool

Lenis

Lenis is a lightweight and efficient library for smooth scrolling. Designed for modern browsers. It supports features like WebGL scroll syncing and parallax effects, making it a great choice for adding stylish and fluid scrolling to your site.

Lenis scrolling library

Themosis

Themosis improves WordPress development by introducing modern practices like MVC and tools from Laravel. It helps you build more organized, scalable WordPress sites with features like custom routing and a CLI from Laravel.

Themosis development framework

WP ORM

WP-ORM is a library that brings Eloquent-style ORM functionality to WordPress. It provides an easy-to-extend ORM with support for core WordPress models like posts, users, and comments. It integrates well with some of the popular frameworks in WordPress such as Bedrock, Themosis, or Wordplate.

WP ORM library

Swapy

Swapy is a JavaScript library that makes any layout draggable and swappable with just a few lines of code. It’s framework-agnostic, meaning you can use it with any JavaScript framework or library including React, Vue, Svelte, and others.

Swapy JavaScript library

The post Fresh Resources for Web Designers and Developers (July 2024) appeared first on Hongkiat.

]]>
72379
10 Alternative Frameworks to Laravel https://www.hongkiat.com/blog/laravel-alternatives/ Tue, 09 Jul 2024 13:00:54 +0000 https://www.hongkiat.com/blog/?p=72287 While Laravel is popular for its rich features and ease of use, there are many other PHP frameworks that might better suit your needs. In this article, we will explore 10 great alternatives to Laravel, each with its own unique strengths and features. Whether you’re looking for something lightweight, highly customizable, or built for high…

The post 10 Alternative Frameworks to Laravel appeared first on Hongkiat.

]]>
While Laravel is popular for its rich features and ease of use, there are many other PHP frameworks that might better suit your needs.

In this article, we will explore 10 great alternatives to Laravel, each with its own unique strengths and features. Whether you’re looking for something lightweight, highly customizable, or built for high performance, I believe there’s an option here for you.

Without further ado, let’s jump in to see the full list.

FrameworkX

FrameworkX logo

FrameworkX is a lightweight PHP microframework created by Christian Luck, designed for building high-performance, real-time applications. It uses an event-driven, non-blocking architecture based on ReactPHP components, making it ideal for high-concurrency and real-time updates such as chat apps and live notifications.

Unlike Laravel, FrameworkX is minimalistic and doesn’t include built-in features like an ORM, templating engine, or expressive helper functions. This minimalism provides flexibility, allowing you to choose and integrate your own preferred libraries for templating, database abstraction, and other functionalities.

Check out our post on how to get started with FrameworkX.

PHP Minimum Requirement: 7.1

PROS

  • High-performance and real-time capabilities
  • Lightweight and minimalistic
  • Event-driven architecture based on ReactPHP components

CONS

  • Requires more manual integration to incorporate other features
  • Less expressive syntax compared to Laravel
  • Requires some getting used to if you are not familiar with event-driven architecture

Visit FrameworkX

CodeIgniter

CodeIgniter logo

CodeIgniter is a lightweight PHP framework originally developed by EllisLab and now maintained by the CodeIgniter Foundation. Similar to Laravel, it follows a more structured architecture and offers many essential features for an MVC framework.

However, it lacks some of Laravel's expressive syntax, like the Eloquent ORM and built-in front-end integrations. Despite this, its simplicity makes it easy to pick up for developers with fair experience in PHP, object-oriented programming, and MVC concepts.

PHP Minimum Requirement: 8.1

PROS

CONS

  • Smaller ecosystem compared to Laravel
  • No built-in ORM
  • No built-in templating engine like Blade
  • Lack of expressive syntax
  • Lack of built-in front-end integration

Visit CodeIgniter

Laminas

Laminas logo

Laminas, formerly known as Zend Framework, is a PHP framework designed for enterprise-grade applications. It offers a collection of professional PHP packages for developing web applications and services. These components are framework-agnostic and comply with PSR (PHP Standard Recommendations), so they can be used outside Laminas.

Laminas differs significantly from Laravel. While Laravel focuses on developer experience, rapid development, and includes full-stack features built-in like Eloquent ORM and Blade, Laminas offers a more modular approach. It provides more flexibility but may require more configuration and setup time compared to Laravel.

PHP Minimum Requirement: 8.1.0

PROS

  • Highly modular and customizable
  • Strong focus on security and enterprise-level features
  • Scalable and suitable for large-scale applications
  • First-party ecosystem: Mezzio, API Tools, and MVC framework

CONS

  • Less expressive syntax
  • No built-in CLI, ORM, and templating engine
  • May require more manual integration for some of its components

Visit Laminas

Slim

Slim framework logo

Slim is a PHP micro-framework developed by Josh Lockhart that focuses on essentials like routing, middleware, and HTTP request handling.

Unlike Laravel's full-stack approach, Slim does not include a full MVC layer, a native template engine, or a database abstraction layer, so you'll need to use your own preferred libraries and components if you need one.

This minimal footprint, however, makes Slim a great choice if you're looking to create lightweight RESTful APIs or microservices.

PHP Minimum Requirement: 8.1

PROS

  • Lightweight and fast
  • Simple and easy to use
  • Ideal for small to medium-sized projects and APIs
  • Extensible with middleware and third-party components

CONS

  • Limited built-in features compared to full-stack frameworks
  • Requires additional libraries for ORM and templating engine

Visit Slim

Nette

Nette framework logo

Nette is a mature and feature-rich PHP framework created by David Grudl. It offers a comprehensive set of tools and components for building web applications, including a powerful templating engine called Latte, forms handling, database abstraction, and many other components.

Nette differs from Laravel in its focus. While Laravel prioritizes developer experience with features like Eloquent ORM, Blade, and the Artisan CLI included and pre-configured, Nette provides its first-party components separately. This allows you to choose which tools and libraries you'd need to include in your project. Despite its modularity, it provides a base application or skeleton to help you quickly start your projects.

PHP Minimum Requirement: 8.1

PROS

  • Matured and battle-tested framework, built since 2004
  • Comprehensive set of tools and components for building websites
  • Provides base or skeleton with flexible structure
  • Powerful templating engine: Latte
  • Good documentation and community support

CONS

  • Less opinionated than Laravel
  • Requires more manual configuration and setup
  • Smaller ecosystem compared to Laravel

Visit Nette

Phalcon

Phalcon framework logo

Phalcon is a unique PHP framework. Unlike the others, it is delivered as a C extension. Designed to optimize speed by bypassing PHP's interpreter and leveraging lower-level system resources directly, it includes full-stack features like a first-party ORM library, router, caching, and more.

Phalcon sets itself apart from Laravel with its architecture as a C extension. Unlike Laravel, which is implemented purely in PHP, Phalcon requires installing a PHP extension, so you need to be comfortable with commands like apt and PHP .ini configuration files to enable the extension. I think Phalcon is ideal for projects where performance is critical and can handle heavy workloads with minimal overhead.

PHP Minimum Requirement: 8.0

PROS

  • High performance due to its nature as a C extension
  • Full-stack features included like ORM, caching, dependency injection, i18n, templating engine, and router

CONS

  • Requires installing a PHP extension, which can be overwhelming for beginners
  • Much smaller ecosystem compared to Laravel

Visit Phalcon

Yii2

Yii2 framework logo

Yii2 is a PHP framework created by Qiang Xue, offering extensive features like an ORM, RESTful API, debugging tools, a boilerplate generator, and much more.

Yii2, I think, is quite similar to Laravel in its approach and principles. Unlike some frameworks where features are in separate modules, Yii2 has them built-in and pre-configured with MVC architecture. It also provides a starter kit with basic interfaces and functionality, similar to Laravel Breeze. Additionally, Yii2 also provides solid first-party modules like the Mailing module, i18n module, Docker for localhost, a first-party templating engine, and front-end integration with Bootstrap.

PHP Minimum Requirement: 7.3

PROS

  • Support for PHP 7.3, if you still need it
  • One of the earliest frameworks in PHP. It’s solid and battle-tested
  • First-party modules and tools included and pre-configured
  • Gii, one of its unique features to generate codes
  • Great documentation and community support

CONS

  • Smaller ecosystem compared to Laravel
  • Less expressive syntax compared to Laravel
  • Has a somewhat unusual namespacing pattern

Visit Yii2

Spiral

Spiral framework logo

Spiral is a high-performance PHP framework developed by the team at Spiral Scout. It is built around RoadRunner, a PHP application server written in Go, which enables it to handle heavy workloads efficiently and reduce the overhead that may commonly occur in traditional PHP applications.

Spiral uses a classic MVC approach and features a routing system similar to Laravel. However, it exclusively runs with RoadRunner, offering twice the performance out of the box compared to typical PHP MVC frameworks. It also includes components like JOBS, Worker, and BirdDog, specifically optimized for RoadRunner, leading to more optimized and faster applications.

PHP Minimum Requirement: 8.1

PROS

  • High performance due to its integration with RoadRunner
  • General-purpose framework that allows you to build MVC, CQRS, Event-Driven, and CLI apps
  • First-party ORM library, CycleORM, which I think looks neat!

CONS

  • Some learning curves, probably requires learning RoadRunner and how it works
  • Smaller ecosystem compared to Laravel

Visit Spiral

Neutomic

Neutomic framework logo

Neutomic is a lightweight PHP framework designed for environments that require long-running processes. Built on top of RevoltPHP, Neutomic supports event-driven, non-blocking I/O operations, making it efficient for handling concurrent tasks.

Neutomic differs from Laravel in its use of an event-driven, non-blocking architecture, while Laravel uses a traditional synchronous design by default. Neutomic requires third-party libraries for features like ORM and templating, whereas Laravel includes these features built-in. To get started with an example of a Neutomic application, you can check out the skeleton repository at neutomic/skeleton.

PHP Minimum Requirement: 8.3

PROS

  • Lightweight and minimalistic
  • High-performance and efficient for handling concurrent tasks
  • Event-driven architecture based on RevoltPHP and Amp components

CONS

  • Requires more manual integration to incorporate other features, but it provides a skeleton to help you get started
  • Less expressive syntax compared to Laravel
  • Requires some getting used to if you are not familiar with event-driven architecture

Visit Neutomic

The post 10 Alternative Frameworks to Laravel appeared first on Hongkiat.

]]>
72287
Introduction to FrameworkX https://www.hongkiat.com/blog/frameworkx/ Mon, 01 Jul 2024 13:00:07 +0000 https://www.hongkiat.com/blog/?p=72250 PHP has come a long way and continues to improve with new features, syntax, and speed. The ecosystem is also expanding, with many developers creating frameworks to simplify the lives of other developers. Popular, full-featured frameworks like Laravel and Symfony exist, as do lightweight microframeworks like FrameworkX. It is a lightweight microframework for PHP that…

The post Introduction to FrameworkX appeared first on Hongkiat.

]]>
PHP has come a long way and continues to improve with new features, syntax, and speed. The ecosystem is also expanding, with many developers creating frameworks to simplify the lives of other developers. Popular, full-featured frameworks like Laravel and Symfony exist, as do lightweight microframeworks like FrameworkX.

It is a lightweight microframework for PHP that uses an event-driven, non-blocking architecture, similar to Node.js which is perfect for high-concurrency and real-time applications like chat apps or live notifications.

In this article, we will explore what FrameworkX is and how it differs from traditional PHP frameworks. Let’s get started!

Getting Started

First, make sure you have PHP and Composer set up on your computer. Once installed, you can add FrameworkX to your project with this command:

composer require clue/framework-x

FrameworkX doesn’t require a complex setup. All you need is a public/index.php file. Here’s a basic example to display “Hello World!” on the homepage:

<?php
require dirname(__DIR__) . '/vendor/autoload.php';
$app = new FrameworkX\App();
$app->get('/', fn () => \React\Http\Message\Response::plaintext("Hello world!\n"));
$app->run();

To run your application, type:

php public/index.php

This command starts a local server using PHP’s built-in server, backed by the ReactPHP Socket component. No need for Nginx or Apache. Your server will run at http://127.0.0.1:8080, and it should display “Hello World!”.

Localhost server setup

Besides plain text, you can also return JSON data. For example:

<?php
require dirname(__DIR__) . '/vendor/autoload.php';
$users = [['name' => 'Jon Doe'], ['name' => 'Jane Doe']];

$app = new FrameworkX\App();
$app->get('/', fn () => \React\Http\Message\Response::json($users));
$app->run();

Async Operations

PHP operations are usually blocking and synchronous, meaning each task must finish before the next one starts. FrameworkX is built on the ReactPHP library.

ReactPHP is a library that provides components such as the EventLoop, Stream, Promise, Async, and HTTP components, which enable asynchronous operations. Thus, tasks can run concurrently without waiting for others to finish. This is ideal for handling multiple connections, HTTP requests, or I/O operations simultaneously.

In this example, we’ve updated our index.php to fetch an API. Instead of using the curl_* functions, we will use the HTTP component to make an asynchronous request.

$app = new FrameworkX\App();
$app->get('/', function () {
    echo "Start\n";
    (new \React\Http\Browser())
        ->get('https://www.hongkiat.com/blog/wp-json/wp/v2/posts')
        ->then(function () {
            echo "End (API)\n";
        });
    echo "End\n";

    return \React\Http\Message\Response::plaintext("Hello world!\n");
});
$app->run();

Normally, an external API request would block the page from rendering until the request completes. However, with the asynchronous operations that the ReactPHP HTTP component handles, the page loads instantly, as evidenced by the log.

Async operations log

This makes FrameworkX capable of handling many more concurrent requests than traditional PHP setups, significantly speeding up page load times. But how fast is it?

Speed

I tested FrameworkX on a basic, inexpensive DigitalOcean droplet with 1 vCPU and 1GB of RAM. It handled around 4,000 requests per second effortlessly.

Concurrency Level:      50
Time taken for tests:   22.636 seconds
Complete requests:      100000
Failed requests:        0
Keep-Alive requests:    100000
Total transferred:      17400000 bytes
HTML transferred:       1300000 bytes
Requests per second:    4417.69 [#/sec] (mean)
Time per request:       11.318 [ms] (mean)
Time per request:       0.226 [ms] (mean, across all concurrent requests)
Transfer rate:          750.66 [Kbytes/sec] received

Even with additional workload, like disk read operations and rendering 100 lists from a JSON file, it still managed around 2700 requests per second.

Concurrency Level:      50
Time taken for tests:   36.381 seconds
Complete requests:      100000
Failed requests:        0
Keep-Alive requests:    100000
Total transferred:      296700000 bytes
HTML transferred:       280500000 bytes
Requests per second:    2748.72 [#/sec] (mean)
Time per request:       18.190 [ms] (mean)
Time per request:       0.364 [ms] (mean, across all concurrent requests)
Transfer rate:          7964.31 [Kbytes/sec] received

I’m pretty sure it could be much faster with better server specifications.

Wrapping Up

FrameworkX is a powerful, lightweight microframework for PHP. It runs asynchronously and is capable of handling multiple tasks efficiently, similar to Node.js. It’s the perfect framework whether you’re building a simple app or complex high-concurrency or real-time applications.

The post Introduction to FrameworkX appeared first on Hongkiat.

]]>
72250
Fresh Resources for Web Designers and Developers (June 2024) https://www.hongkiat.com/blog/designers-developers-monthly-06-2024/ Sun, 30 Jun 2024 15:00:16 +0000 https://www.hongkiat.com/blog/?p=72258 It’s the time again to share new resources, tools, and libraries with our fellow web developers. PHP has regained popularity and sparked numerous discussions once more. Unlike ten years ago, PHP has grown significantly with new features and an expanding ecosystem. This edition features several PHP libraries and tools, alongside various JavaScript libraries and frameworks…

The post Fresh Resources for Web Designers and Developers (June 2024) appeared first on Hongkiat.

]]>
It’s the time again to share new resources, tools, and libraries with our fellow web developers.

PHP has regained popularity and sparked numerous discussions once more. Unlike ten years ago, PHP has grown significantly with new features and an expanding ecosystem. This edition features several PHP libraries and tools, alongside various JavaScript libraries and frameworks that connects these two languages together.

Without further ado, let’s go into the details.

Fresh Resources for Web Designers and Developers (May 2024)

Fresh Resources for Web Designers and Developers (May 2024)

It's that time again to check out some tools, libraries, and frameworks for our web developer friends. This... Read more

AstronWind

AstroWind is a free, open-source template for building websites with Astro and Tailwind CSS. It supports dark mode, RTL, and includes a blog with MDX, categories, tags, social sharing, and an automatic RSS feed. Additionally, it offers image optimization, sitemap generation, Open Graph tags, and integrations with Google Analytics, making it easy and quick to launch your website.

AstroWind template screenshot

Drei

drei is a popular helper library for react-three-fiber, which is a React renderer for Three.js. It provides components for common tasks such as loading models, creating controls, handling interactions, setting up lighting, and other utilities. A great library that could simply creating 3D scenes on your website.

Drei library logo

33 JavaScript Concept

A curated list of 33 fundamental concepts for JavaScript developers. It provides a comprehensive list of JavaScript concepts that are essential to help you understand the language better. It includes explanations and resources for each concept and principles, making it a valuable reference whether you are beginners or experienced developers.

33 JavaScript Concepts logo

WP Starter Plugin

WP Starter Plugin is a starter kit designed to help WordPress developers easily create modern and well-organized plugins. It promotes modern PHP practices like using namespaces, Composer, and autoloaders. The kit includes a structured foundation with a predefined folder structure, boilerplate code, and pre-configured tools like RectorPHP and Webpack.

WP Starter Plugin logo

Laravel Best Practices

This comprehensive list of best practices for developing applications with Laravel helps developers write clean, and maintainable Laravel application by following industry standards. It covers various topics such as the application structure, configurations, Eloquent ORM, testing, and security. A great resource for both beginners and experienced developers to improve their skill to build high-quality applications.

Laravel Best Practices logo

Firefly III

Firefly III is a free and open-source personal finance manager that helps you manage your finances efficiently. Built on top Laravel, it features a double-entry bookkeeping system, allowing you to easily enter and organize your transactions in multiple currencies. A solid finance application whether for your own business or to build for you clients.

Firefly III logo

PHP Image Processing

Intervention Image is a PHP library designed to make image processing easy. It provides a unified API for GD library or Imagick to work with common tasks like creating, editing, and composing images. It also supports animated images, is framework-agnostic, and complies with PSR-12 standards, making it versatile and easy to integrate into any PHP project.

Intervention Image logo

Nelmio

Alice is a library that helps you create large amounts of fake data for developing or testing your project. Backed by FakerPHP, it generates complex and constrained data, and you can choose whether to use Yaml or PHP for the data generation. This makes it easy for your team to tweak the fixtures as needed, and ensures that everyone can quickly and efficiently set up realistic data for various use cases in your tests.

Nelmio Alice logo

Psysh

PsySH is an interactive debugger and REPL (Read-Eval-Print Loop) for PHP. It allows you to execute PHP code in real-time, inspect objects, test functions, and debug directly from the command line. It comes with features like code completion, immediate feedback, and a command history. It’s compatible with modern PHP frameworks and libraries, making it easier to develop and debug PHP applications.

PsySH logo

Hyperf

Hyperf is a high-performance PHP framework for building web applications, microservices, and APIs. It uses Coroutines to handle many connections efficiently. It offers features like dependency injection, annotation-based routing, and asynchronous programming. It’s built to use the latest PHP features, making it a great choice for creating fast and scalable applications with PHP.

Hyperf logo

Slugify

Slugify is a PHP library that transforms strings into URL-friendly slugs with support for over 30 languages. It’s lightweight, has no external dependencies, and is compatible with PHP8 and higher. It also integrates with frameworks like Symfony, Laravel, Twig, and others, making it easy to generate clean and SEO-friendly URLs for your web applications.

Slugify logo

MingleJS

MingleJS is a library that allows you to combine Laravel Livewire with React or Vue components in a Laravel application. Livewire lets you build dynamic interfaces using server-side code, and with MingleJS, you can seamlessly integrate React or Vue components into your Livewire projects. This gives you the flexibility to use the best features of both server-side and client-side frameworks.

MingleJS logo

Shittier

Shittier is a tool that deliberately makes your code look messy. Unlike tools that aim for neatness like Prettier, Shittier randomizes indentation, mixes up casing, and messes with spacing. You probably won’t use it in production, it’s good to know tool for fun, and probably good for performing demo and tests in some situations.

Shittier tool screenshot

Laravel Orchid

Laravel Orchid is a powerful tool for creating admin panels. It comes with a variety of customizable UI components like form inputs and data grids, making it easy to build and extend your application’s features without spending time on repetitive tasks.

Laravel Orchid logo

VSCode Blade Formatter

vscode-blade-formatter is a VSCode extension that formats Blade files with a specific style. It automatically indents markup inside directives, adds spacing to Blade template markers, and supports PHP 8 features and PSR-2 formatting. It also sorts Tailwind CSS classes based on your tailwind.config.js. A great VSCode plugin to make your Blade codes clean and consistent.

VSCode Blade Formatter logo

TwillCMS

Twill is an open-source CMS for Laravel that simplifies building custom admin panels. It features a user-friendly interface, flexible content management, drag-and-drop functionality, media handling, customizable forms, and multilingual support. Twill integrates seamlessly with Laravel, making it easy for developers to create and maintain content-rich websites efficiently.

Twill CMS logo

Bashunit

bashunit is a simple and modern testing library for Bash scripts to ensure your scripts work reliably. It comes with an intuitive API, clear documentation, and it simplifies creating and managing tests, no matter how big or complex your Bash script is.

Bashunit logo

Pixelfed

Pixelfed is an open-source, social media platform that focuses on photo sharing. Designed to be an alternative to Instagram with decentralized approach where users can host their own instances and still interact with others across the network. A perfect app, if your client is asking you to develop a social media.

Pixelfed logo

SkeletonDev

Skeleton is a toolkit for building accessible web UI with Svelte and Tailwind CSS. It leverages Svelte and SvelteKit built-in features like the components, stores, and actions. And with Tailwind CSS you can easily customize style components with the Tailwind’s utility classes. An overall great app with .

Skeleton toolkit logo

SVGViewer

SVGViewer is an all-in-on web application for SVG. You can use it to view SVGs or optimize them. Additionally, it offers conversion to various formats such as React, React Native, PNG, and Data URI. It’s a great tool for managing and transforming SVGs to suit different your different needs.

SVGViewer app screenshot

The post Fresh Resources for Web Designers and Developers (June 2024) appeared first on Hongkiat.

]]>
72258
How to Publish Website on Github Pages in Three Simple Steps https://www.hongkiat.com/blog/publishing-github-page/ https://www.hongkiat.com/blog/publishing-github-page/#comments Fri, 14 Jun 2024 13:00:15 +0000 https://www.hongkiat.com/blog/?p=27780 Github Pages offers a valuable service by allowing you to host a static website directly from a Git repository. It’s an ideal platform for solo developers to showcase portfolios, support open-source projects, or disseminate information about educational institutions or organizations. Many prominent projects utilize Github Pages for hosting, including well-known ones like Bootstrap, NormalizeCSS, and…

The post How to Publish Website on Github Pages in Three Simple Steps appeared first on Hongkiat.

]]>
Github Pages offers a valuable service by allowing you to host a static website directly from a Git repository. It’s an ideal platform for solo developers to showcase portfolios, support open-source projects, or disseminate information about educational institutions or organizations.

Many prominent projects utilize Github Pages for hosting, including well-known ones like Bootstrap, NormalizeCSS, and Yelp.

This tutorial will walk you through the steps to create and publish a straightforward site using Github Pages. It is assumed that you have a basic understanding of Git and its commands, such as how to create and push commits to a remote repository. If not, I recommend checking out our guide: 30 Basic Git Commands You Should Know.

Let’s get started!

Step 1: Create a Repository

First, you need a Github account to create a repository. You can name the repository anything you like; there are no specific naming requirements.

Creating a new repository on Github

After creating the repository, the next step is to clone it to your local computer. If you have the Github Desktop application installed, you can easily accomplish this by going to File > Clone Repository within the application.

Cloning a repository using Github Desktop

Alternatively, you can clone the repository using the git command-line interface (CLI), for example:

git clone https://github.com/hongkiat/fuzzy-adventure.git

Step 2: Create the Main Page

To set up a homepage, Github primarily looks for a file named index.html. It can also utilize index.md or README.md. This file can be placed at the root of your repository or within a subdirectory to separate your site from the main source code—commonly in the docs or site directory.

In this example, I’ll demonstrate adding an index.html file in the docs directory, supplemented with styles and scripts from Bootstrap.

Adding files to the docs directory

With the files in place, we can now add and push them to the Github repository.

Step 3: Configure Page Deployment

In your Github repository, navigate to Settings > Pages. Here, select the source you wish to deploy as Github Pages. Since we’ve placed the index.html file in the docs directory, choose the appropriate branch and set the directory to /docs under the “Build and deployment” section.

Configuring build and deployment settings

That completes the setup for your Github Pages site. The site will be accessible through a URL pattern provided by Github. For example, if your repository is at github.com/hongkiat/fuzzy-adventure, then your Github Pages site will be at hongkiat.github.io/fuzzy-adventure.

Preview of the Github Pages site

Bonus: Using a Custom Domain

Using a custom domain for your Github Pages site provides a personalized URL that’s easier to remember and enhances your site’s branding. Here’s how to set it up.

Step 1: Add DNS Record

To begin, add a DNS record to link your custom domain to Github Pages. For instance, if you want to use fuzzy-adventure.hongkiat.net, you’ll need to create a CNAME record in your domain’s DNS manager that points to hongkiat.github.io.

If you’re unsure where to find your DNS manager or how to add a new DNS entry, please contact your domain registrar for assistance.

Step 2: Wait for Domain Propagation

After setting the DNS record, it takes some time for the changes to propagate, which can vary from a few minutes to 24 hours. You can monitor with DNS propagation tools like WhatsMyDNS or by using the command below:

dig fuzzy-adventure.github.io +nostats +nocomments +nocmd

Once the DNS propagation is confirmed, you might see results similar to this:

Results of DNS propagation check for custom domain
Step 3: Add Domain to Repository

After DNS propagation completes, inform Github about your custom domain. Go to your repository’s Settings, head to the Pages section, and enter your custom domain in the Custom Domain field. Github will verify the domain and set it up. Once verified, you can also secure your site by enabling the “Enforce HTTPS” option.

Verifying custom domain in Github repository settings

Now your Github Pages site should be accessible via your custom domain!

The post How to Publish Website on Github Pages in Three Simple Steps appeared first on Hongkiat.

]]>
https://www.hongkiat.com/blog/publishing-github-page/feed/ 3 27780
Introduction to FrankenPHP https://www.hongkiat.com/blog/frankenphp/ Thu, 13 Jun 2024 13:00:53 +0000 https://www.hongkiat.com/blog/?p=72086 FrankenPHP is a new PHP runtime designed to modernize PHP architecture. It is built on top of Caddy, and it includes Caddy’s built-in features such as automatic SSL, native support for HTTP3, and Early Hints. It also supports compression methods like Gzip, Brotli, and Zstd. Additionally, it features a built-in Mercure hub, enabling real-time push…

The post Introduction to FrankenPHP appeared first on Hongkiat.

]]>
FrankenPHP is a new PHP runtime designed to modernize PHP architecture. It is built on top of Caddy, and it includes Caddy’s built-in features such as automatic SSL, native support for HTTP3, and Early Hints. It also supports compression methods like Gzip, Brotli, and Zstd. Additionally, it features a built-in Mercure hub, enabling real-time push events without the need for additional libraries or SDKs.

With all these features, FrankenPHP promises faster performance out-of-the-box, simpler configuration, and an improved Developer Experience (DX) compared to traditional PHP setups like PHP-FPM.

Here is how it compares:

Feature FrankenPHP PHP-FPM
Performance Great performance with worker mode and direct communication with the web server, reducing latency. Good performance, but it requires FastCGI communication which may introduce some overhead.
Scalability Excellent scalability. It can be compiled into a single binary, making it easy to run on serverless architectures. Good scalability, but often requires manual tuning of process pools on both the PHP-FPM and the web server side (usually Nginx).
Complexity Generally simple with minimal configuration overhead, thanks to Caddy’s configuration. Somewhat complex, involving separate configurations for PHP-FPM and the web server (usually Nginx).

Getting Started

Running FrankenPHP requires Docker. It is pre-packaged in a single Docker image, so you don’t need to install PHP binaries and modules yourself. Once you have Docker installed, you need to create the index.php file, which will serve as the homepage.

In this example, let’s keep it simple. I will just print the PHP info table.

<?php 
    phpinfo();

You can now run the following Docker command to start the site:

docker run -v $PWD:/app/public -p 80:80 -p 443:443 -p 443:443/udp dunglas/frankenphp

This command mounts the current directory to the /app/public directory in the Docker container and maps ports 80 and 443 from the container to the host machine, as well as 443/udp to enable HTTP3.

Caddy also generates SSL certificates and loads the site over HTTPS. However, your browser won’t recognize the SSL certificate for localhost, so you will receive an error when you load the site.

SSL error message

There are a few ways we can create a workaround to let HTTPS load on localhost. The easiest and quickest method that works in different scenarios is to enable the flag in Chrome at chrome://flags/#allow-insecure-localhost. Restart Chrome, and then reload the page.

Loaded localhost site

Now, your localhost runs on the FrankenPHP server API. If you inspect the response in Chrome, you’ll see that it’s compressed with zstd and served through HTTP3.

It’s impressive that we can have it running with just a single command.

Running a Framework

FrankenPHP is not limited to just running a simple PHP file. It is compatible and can run a full-fledged PHP framework such as Symfony, Laravel, or any other PHP framework. The only thing you need to do is mount the framework directory to the /app/public directory in the Docker container. For example, to run a Laravel application, you can run the following command:

docker run -v $PWD:/app -p 80:80 -p 443:443 -p 443:443/udp dunglas/frankenphp

It’s that simple. FrankenPHP will automatically detect the files and serve the Laravel application.

Laravel app running

Wrapping Up

All these features like automatic SSL, HTTP3, and modern compression make developing and running PHP applications much easier and faster. If you’re coming from nginx or Apache, like me, the only thing you need to get used to is the Caddyfile configuration. But once you get accustomed to it, you’ll find it much simpler and more powerful than traditional web server configurations.

I think FrankenPHP is a great choice for modern PHP applications. It’s fast, scalable, and easy to use. I highly recommend it for any PHP developers looking to give it a try.

The post Introduction to FrankenPHP appeared first on Hongkiat.

]]>
72086