© Gunnard Engebreth, Satej Kumar Sahu 2023
G. Engebreth, S. K. SahuPHP 8 Basicshttps://doi.org/10.1007/978-1-4842-8082-9_13

13. Introduction to Frameworks

Gunnard Engebreth1   and Satej Kumar Sahu2
(1)
Madison, WI, USA
(2)
Bangalore, India
 

After having learned in the previous chapters how to build a website, in this chapter you will focus on programming development frameworks. You will learn what they are and when to use them.

This chapter consists of the following sections:
  • Introduction to Frameworks

  • Pros and Cons of Frameworks

  • MVC Pattern

  • Different Layers of a Framework

  • Different Types of Frameworks

  • Introduction of PHP Standard Recommendation (PSR)

  • PHP Frameworks

Introduction to Frameworks

Until now, you have built the different layers of an application: the UI components to parse values and display the view pages, connect to the database and fetch data, authenticate use, and maintain sessions. If you observe, these contextual areas are reusable structures and elements that are used in every project or application based on different use cases.

They have structural value but do not add value in terms of helping developers and teams develop new features and business logic. Recognizing the recurrence of these common structural elements, many smart people felt that they could be developed and packaged together so that these structures could interface with each other and be reused. In essence, they created a framework, which is a supporting structure that helps you get started developing your applications, thus delivering business value, instead of you spending time developing a session layer, a database connection layer, and then a security component.

Frameworks use a lot of best practices and design patterns to allow developers to quickly use them to solve problems.

With this said, should you build a framework for your own use case? This may not be necessary since all frameworks nowadays provide a way to install any packages you might need but are not present already within the framework. They also allow you to build custom layers by extending the framework or plugin systems. If they are open source, if a need arises, you can fork them and use the foundations of existing frameworks to build upon them.

Pros and Cons of Frameworks

Frameworks have a lot to offer, but they are not without drawbacks. In this section, you’ll explore the pros and cons.

Pros of Using Frameworks

There are many benefits to using frameworks:
  1. 1.

    Speeds up application development

    Frameworks help you to focus on working on new features/requirements instead of building reusable patterns and testing the frameworks, authentication, and authorization processes. This saves a lot of time in terms of building the foundation of a secure, standard code base, which a framework provides.

     
  2. 2.

    Simplifies application maintenance

    With the core foundation being maintained by the framework team, it becomes easy for the development team to maintain the application features and upgrade the core framework from time to time.

     
  3. 3.

    Decoupled patterns

    Frameworks come preloaded with a variety of patterns, which resemble a decoupled system design like having a message queue abstraction on top of a variety of message queue platforms, thus providing state-of-the-art coding structures that otherwise would be need to be developed by developers.

     
  4. 4.

    Updated patches

    Frameworks are built and maintained by a lot of internal as well as community-based open source developers, QA engineers, and other smart people who take care of handling changes, upgrading packages, integrating new features as and when they become relevant, and patching security issues. Given the knowledge of such a community team, it becomes a piece of cake to get these changes just with a version upgrade.

     
  5. 5.

    Task automation

    Frameworks provide command-line tools to create base code for new features like a unit test case or a controller with a standard structure, which can then be modified by you for your application-specific requirements. This makes it very easy to quickly prototype and build components.

     

Cons of Using Frameworks

As alluded to earlier, frameworks do have some potential drawbacks:
  1. 1.

    Performance of the application is affected.

    Frameworks comprise a large amount of code for the base structure, which helps to quickly bootstrap your projects. On the other hand, there is a performance penalty since many components may not be applicable to your project but still are loaded during packaging and run time.

     
  2. 2.

    Lack of support or active development

    A framework may have an active current development cycle but things may change in the future. It’s crucial to consider past and current patterns of the framework team, development, and activity.

     
  3. 3.

    Learning curve

    Learning frameworks is a fun and challenging task. Some frameworks are very intuitive while others require a lot of configuration before starting. With many base and advanced components and concepts, learning a framework takes time on the part of the development teams.

     

MVC Pattern

MVC stands for the Model, View, and Controller Pattern. It’s a very handy and useful design pattern that many frameworks use for separation of concerns. In previous chapters, you divided your code into UI, routing, processing, and a business logic layer. Similarly, frameworks separate out code into these logical structures and allow integration and control flow between them through many standard, evolved, and secure practices.

As shown in Figure 13-1, when any request is received by a PHP server, it hits the controller, which is usually the routing layer responsible for defining the GET, POST, and other REST verb-based API endpoints. The controller functions for respective endpoints receive the request and then call the Model layer to fetch any data or run any business logic after fetching data from another service. After the controller receives this data, it sends it to the View layer, which contains your UI code and generates the dynamic UI based on the model data sent to it. Once the View layer is processed, this is sent as response back to the browser or user.
Figure 13-1

The Model-View-Controller architecture

Different Layers of a Framework

  1. 1.

    MVC layer

    All major frameworks use some variation of the MVC pattern as the core structural component to manage requests and control flow.

     
  2. 2.

    Dependency injection

    With many core components, like authentication/authorization/entity access, it becomes crucial to have a centralized logic to access these entities/components through dynamic injection rather than initializing them in each file where they are used, thus enabling reuse and manageability.

     
  3. 3.

    Authentication/authorization

    Authentication/authorization allows developers to validate users and also implement authorization through standard practices and in many cases also allow integration to Active Directory and other third-party services.

     
  4. 4.

    Session management

    Session management helps to validate users once they have logged in. In many cases, this is achieved through token-based authentication using JWT and other standards.

     
  5. 5.

    Database libraries

    Frameworks provide database libraries to connect to a variety of databases.

     
  6. 6.

    Test framework

    Frameworks also provide a test framework to write unit, functional, and integration tests. These tests help to mock and stub internal components, thus allowing developers to practice TDD-based design development.

     
  7. 7.

    Package management

    Composer is the central piece of library management, and it allows reusability of many standard libraries across frameworks, thus helping with interoperability among frameworks.

     
  8. 8.

    Other

    There are many other components like guard rails, message queue management, and caching, that are part of the core components.

     

Different Types of Frameworks

Let’s quickly run through some of the different frameworks available to PHP developers.

Based on use case:
  1. 1.

    REST API-based frameworks

    Many back-end applications nowadays just provide a RESTful interface that is accessed from a front-end application built on React or Angular or another front-end library or framework. So many frameworks provide an out-of-box solution to create REST API backends.

    Examples: Lumen, Silex, Slim, Guzzle, Symphony

     
  2. 2.

    FULLSTACK-based frameworks

    These frameworks have some UI components integrated to allow you to develop UI code from within the platform.

    Examples: Laravel, CakePHP, CodeIgniter, Laminas

     
Based on initial components packaged:
  1. 1.

    Micro frameworks:

    These frameworks provide you with the bare minimum base to start, plus guidelines. These frameworks are very light. Based on your use case, you can choose different packages and design patterns. This will require some extra effort and knowledge on your part to build these patterns.

    Example: Slim

     
  2. 2.

    Full-fledged frameworks

    These frameworks come with all the fire power. In many cases, you may not need some of these packages but they are still included when deploying your application. The downside is the huge size of the framework, but it’s helpful for teams to use the already established patterns and styles.

    Example: Laravel

     

Role of Composer

With the emergence of many frameworks, there was a need to also have many third-party libraries for integration to different APIs. They can be integrated into frameworks through extensions and following framework-specific methodology. This can be quite cumbersome since it requires extensive knowledge of the inner workings of the framework plus the external API. In addition, you must handle the standards, best practices, and security while doing so. This is not the core responsibility of the developer. So, PHP introduced a package manager that can be used to install third-party packages and libraries that are created by community and third-party vendors. With it, developers can reuse these libraries and get updates as and when the source team publishes them. This helps in having a versioned library to be used across different frameworks.

Link: https://getcomposer.org/

Installing Composer is very easy. It just takes these few commands at https://getcomposer.org/download/.

All PHP frameworks use Composer for internal dependencies. As such, they come prepackaged with a Composer configuration, which can be extended.

When Composer is used, it creates a composer.json file that stores all the installed packages with their respective version in the JSON format.

Introduction of PHP Standard Recommendation (PSR)

With the emergence of so many PHP frameworks and the use of Composer for package management, to make the process easy for developers to use different frameworks and for interoperability, there needed to be a common standard on which all these frameworks should be based. This led to the creation of PHP Standard Recommendations (PSR), a PHP specification published by the PHP Framework Interoperability Group (PHP-FIG). It serves as the standardization of programming concepts in PHP.

The goal is to enable interoperability of components and packages. The PHP-FIG was established and formed by several PHP framework founders. The general idea is “moving PHP forward through collaboration and standards.”

The full list of standards can be found at www.php-fig.org/psr/#numerical-index. Some are deprecated and some are in draft status. The current active ones can be found at www.php-fig.org/psr/#index-by-status.

Here are a few principle areas of PSRs:
  1. 1.

    Autoloading

    Autoloading helps load classes and libraries by resolving namespaces to their respective file system paths.

    Associated PSRs: PSR-4 Improved Autoloading

     
  2. 2.

    Interfaces

    Interfaces help in establishing contracts between shareable code structures.

    Associated PSRs:
    • PSR-3: Logger Interface

    • PSR-6: Caching Interface

    • PSR-11: Container Interface

    • PSR-13: Hypermedia Links

    • PSR-14: Event Dispatcher

    • PSR-16: Simple Cache

     
  3. 3.

    HTTP

    A standards-based approach to handle HTTP requests and responses

    Associated PSRs:
    • PSR-7: HTTP Message Interfaces

    • PSR-15: HTTP Handlers

    • PSR-17: HTTP Factories

    • PSR-18: HTTP Client

     
  4. 4.

    Coding styles

    Coding standards to reduce cognitive friction and better readability

    Associated PSRs:
    • PER Coding Style

    • PSR-1: Basic Coding Standard

    • PSR-12: Extended Coding Style Guide

     

PHP Frameworks

The following are a few popular and widely used PHP frameworks. You will use a few of them in later chapters.

Choosing a Framework

With a plethora of frameworks available, it may be a bit confusing. How do you select the right one? Here are a few points to consider:
  1. 1.

    Application/business use case compatibility

    There are many use cases, and each application is unique in terms of its requirements. Some applications are more content-specific. For example, managing a blog for a team for which WordPress would be more suitable. In another case, a team may need to build a RESTful application for which Lumen or a similar framework may be helpful.

     
  2. 2.

    Developer skill set

    The core skill set of the development team also plays a principal role. If the team already knows a particular framework or design patterns particular to a framework, it’s easy to reuse the existing skill set.

     
  3. 3.

    Learning curve

    Timelines of projects play a major role in terms of framework choice. Pick a framework that has a suitable learning curve so you can quickly start building your project.

     
  4. 4.

    Documentation

    Documentation plays a very important role. A framework without good documentation is like wandering in a forest without a map. Good documentation gives developers confidence to quickly experiment and follow up with a deep dive.

     
  5. 5.

    Testing framework

    A framework should be integrated with a test framework that can be used to write integration, functional, and unit tests. Many frameworks provide easy integration of tests and also help with mocking internal functionality of the framework so as to easily and quickly run unit tests.

     
  6. 6.

    Community support

    A community of internal, external, and open source commitment in terms of support and query answering in different forums like Stack Overflow is a very good indicator of people using it and being interested in answering questions related to problems they may have already faced, thus helping development teams gain confidence.

     
  7. 7.

    Active release/development

    A framework that is actively developed and has an active approach towards security and bug fixes on a regular basis gives confidence towards a future where this product will be supported on an ongoing basis.

     
  8. 8.

    Licenses

    It’s very important to review the licenses of the framework related to its code sharing, editing, open source nature, and details relevant to production use.

     
  9. 9.

    Customization/extensibility

    The ability of the framework to customize and extend core features to support unique extensions as per application requirements is very important.

     
  10. 10.

    Convention vs. customization

    There is always a choice between convention and customization. Some frameworks are very particular about conventions and rules to be followed with the intention to reduce setup and help with a quick start on projects, while other frameworks choose a more open structure that can be customized as per your choice and application structure.

     
  11. 11.

    IDE support

    With many popular IDEs nowadays, it becomes important to support the generation of code snippets through shortcuts instead of copy-and-paste to improve developer productivity.

     
  12. 12.

    Blogs/tutorials

    Many frameworks provide their own internal blogs and tutorials to leverage the expertise of the core open community team. They also announce new resources, features, and use cases on an ongoing basis through news channels, announcements, and mailing chains.

     
  13. 13.

    Test coverage

    It’s important to validate that the core framework has full test coverage, which lays the importance of the core teams TDD-based development practices for the framework and also is an indicator of the quality of the core framework.

     

Summary

In this chapter, you learned why frameworks are an important part of the software development life cycle and make the life of developers easier and more fun by allowing them to reuse existing components of a framework to quickly start building new features and innovations. You explored why the choice of a framework is very important. It must be done by considering a variety of key points as well as the application to be built.

In the next chapter, you will focus on the Laravel PHP framework, which is a very popular web application framework that is easy to use and has an elegant syntax.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset