Skip to content

Commit

Permalink
Merge pull request #262 from bearsunday/tech
Browse files Browse the repository at this point in the history
Add technical manual for BEAR.Sunday in Japanese
  • Loading branch information
koriym authored Apr 17, 2024
2 parents 531690d + 000f212 commit 656a4f0
Show file tree
Hide file tree
Showing 4 changed files with 399 additions and 0 deletions.
3 changes: 3 additions & 0 deletions _includes/manuals/1.0/en/contents.html
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@
<li class="nav-item">
<a class="nav-link {% if page.permalink == '/manuals/1.0/en/' %}active{% endif %}" href="/manuals/1.0/en/">Introduction</a>
</li>
<li class="nav-item">
<a class="nav-link {% if page.permalink == '/manuals/1.0/en/tech.html' %}active{% endif %}" href="/manuals/1.0/en/tech.html">Technology</a>
</li>
<li>
<a class="nav-link {% if page.permalink == '/manuals/1.0/en/version.html' %}active{% endif %}" href="/manuals/1.0/en/version.html">Version</a>
</li>
Expand Down
3 changes: 3 additions & 0 deletions _includes/manuals/1.0/ja/contents.html
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@
<li class="nav-item">
<a class="nav-link {% if page.permalink == '/manuals/1.0/ja/' %}active{% endif %}" href="/manuals/1.0/ja/index.html">イントロダクション</a>
</li>
<li class="nav-item">
<a class="nav-link {% if page.permalink == '/manuals/1.0/ja/tech.html' %}active{% endif %}" href="/manuals/1.0/ja/tech.html">技術</a>
</li>
<li class="nav-item">
<a class="nav-link {% if page.permalink == '/manuals/1.0/ja/version.html' %}active{% endif %}" href="/manuals/1.0/ja/version.html">バージョン</a>
</li>
Expand Down
195 changes: 195 additions & 0 deletions manuals/1.0/en/15.tech.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,195 @@
---
layout: docs-en
title: Technology
category: Manual
permalink: /manuals/1.0/en/tech.html
---
# Technology

This chapter explains the features and technical characteristics of BEAR.Sunday.

## Dependency Injection (DI)

Dependency Injection (DI) is a pattern that automatically resolves object creation and dependencies by the framework, reducing code coupling and improving testability and maintainability. BEAR.Sunday's DI uses [Ray.Di](https://github.com/ray-di/Ray.Di), an independent package that incorporates the design philosophy of Google's Guice DI framework and covers almost all its features.

What sets this framework's DI apart from other frameworks is that auto-wiring based on rules is the default, without the user directly touching the container. Other features include:

* Context-sensitive bindings allow dynamic changes to application behavior.
* DI compilation generates PHP code for instance generation, minimizing runtime overhead.
* Object dependencies can be visualized in a graph.
* Instances are generated based on rules. Users do not need direct access to the container even at compile (configuration) time.

## Aspect Oriented Programming (AOP)

Aspect Oriented Programming (AOP) is a pattern that realizes flexible applications by separating core concerns such as business logic from cross-cutting concerns such as logging and caching. BEAR.Sunday's AOP uses Ray.Aop, an independent package that declaratively binds cross-cutting processes by attaching PHP attributes to classes and methods.

AOP is one of the most misunderstood technologies. Its raison d'etre is not to break order by ignoring constraints, but to complement areas where object orientation is not suited, such as exploratory function assignment and separation of cross-cutting processes, and to create application-wide constraints. In other words, it is one of the paradigms that can be designed as constraints of the application framework.

Other features of AOP include:

* Cross-cutting processes can be bound to classes and methods that match search criteria such as class and method names.
* Using PHP attributes allows declarative description of cross-cutting processes.
* Classes and methods matching the search criteria can be dynamically changed.

## Resource Oriented Architecture (ROA)

BEAR.Sunday's ROA is an architecture for realizing RESTful APIs in the internal structure of web applications and is at the core of BEAR.Sunday's design principles. It is a hypermedia framework and also an object as a service. Like the Web, all data and functions are treated as resources and operated on with specified interfaces such as GET/POST/PUT/DELETE.

### Uniform Interface

Access to resources is done using HTTP methods (GET, POST, PUT, DELETE). These methods specify the operations that can be performed on resources and provide a common interface regardless of the type of resource.

- GET: Retrieves the current state of the resource
- POST: Performs non-idempotent operations on the resource (e.g., creation)
- PUT: Performs idempotent operations on the resource (e.g., creation or update)
- DELETE: Deletes the resource

### Hypermedia

Links between resources are represented by hypermedia. Each resource representation includes links, and clients can traverse the application by following these links. This reduces coupling between client and server and increases application flexibility. Content can also be represented in a tree structure by linking internally.

### Separation of Value and Representation

In BEAR.Sunday's ROA, resource values and representations are clearly separated. Resource values are managed by the application's domain logic, and representations are for expressing those values in various formats (JSON, XML, HTML, etc.). This separation decouples domain logic and presentation logic, improving application maintainability and extensibility.

### Page Resources and App Resources

In BEAR.Sunday's ROA, resources are classified into page resources and app resources.

- Page resources: Resources that primarily represent HTML and are intended to be accessed from a web browser. These are the resources that make up the user interface.
- App resources: Resources that make up the application's backend and primarily represent JSON and XML. They are intended to be accessed by other applications and services.

Separating page resources and app resources allows independent development and deployment of user interfaces and application logic. In addition, by reusing app resources, a consistent backend can be provided for multiple user interfaces (web browsers, mobile apps, other services, etc.).

Using BEAR.Sunday's ROA, scalable and loosely coupled applications can be built in accordance with web design principles. Separating value and representation allows independent development and testing of domain logic and presentation logic, improving application quality and development efficiency. Separating page resources and app resources allows independent development and deployment of user interfaces and application logic, improving application flexibility and extensibility.

### Differences from MVC

BEAR.Sunday's ROA takes a different approach than traditional MVC architecture.

* MVC controllers tend to have multiple responsibilities, but BEAR.Sunday's resources follow the Single Responsibility Principle (SRP) with DI and AOP, distributing responsibilities.
* MVC controllers perform various operations, but BEAR.Sunday's resources have semantic methods (semantically clear methods) that clarify operations.
* BEAR.Sunday uses embedded resources to declaratively show the containment relationships of content. This not only makes the relationships between resources explicit, but also allows dependency resolution for cache invalidation.
* BEAR.Sunday resources themselves have the responsibility of representation, increasing self-containment.
* BEAR.Sunday resources declare relations to provide possible operations (affordances). Clients can dynamically manipulate resources using this as a clue. It is self-descriptive.
HAL (Hypertext Application Language) is adopted for links to standardize links between resources.
* Unlike MVC models, it can be directly called from a variety of clients, including the console.
* There is no need to build HTML sites and API sites separately; the same resources can be used to simultaneously build HTML sites and API sites.

## ROA-based Event-Driven Cache Strategy Integrated with Modern CDN
BEAR.Sunday realizes an advanced event-driven cache strategy by integrating with instant-purgeable CDNs such as Fastly, with the resource-oriented architecture (ROA) at its core. The ROA approach enables this by giving methods clear semantics and using embedded links to clarify dependencies between resources.

### Cache Invalidation by Semantic Methods
In BEAR.Sunday's ROA, each resource operation is given semantics (semantic roles). For example, the GET method retrieves a resource, and the PUT method updates a resource. These methods work together in an event-driven manner to efficiently invalidate related caches. For instance, when a specific resource is updated, that change automatically propagates to other resources that depend on it, and related caches are invalidated. This maintains data consistency and freshness, ensuring users are provided with the most up-to-date information.

### Visualization of Dependencies by Embedded Links
In ROA design, resources can contain links to other resources, transparently showing the dependencies between resources to the client. By leveraging this link information, it is possible to instantly determine which resources are affected when cache invalidation is necessary, enabling efficient cache management.

### Cache Key Generation by Argument Declaration
In BEAR.Sunday, resource method arguments are clearly declared. This allows generating unique cache keys based on the resource state and request parameters. Cache key generation is an important mechanism for accurately identifying and invalidating specific caches when a resource state changes. This allows necessary parts to be quickly updated while avoiding unnecessary cache deletion.

### Identity Confirmation and Rapid Response with ETag
By setting the ETag before the system boots, content identity can be quickly confirmed, and if there are no changes, a 304 Not Modified response is returned. This is an effective technique for reducing network load and improving user experience.

### Partial Updates with Donut Caching and ESI
BEAR.Sunday adopts a donut caching strategy and uses Edge Side Includes (ESI) to enable partial content updates at the CDN edge. This technology allows dynamically updating only necessary parts without re-caching entire pages, significantly improving performance and caching efficiency.

Thus, BEAR.Sunday and Fastly's integrated ROA-based caching strategy realizes advanced distributed caching while improving application performance and fault tolerance. This allows users to experience consistent responsiveness and data consistency under any circumstances.

## Ease of Testing

* Each resource is independent, and testing is easy due to the stateless request nature of REST.
* Resource state and representation are separated, so only the resource state can be tested.
* API testing can be performed by following hypermedia links, and testing can be done with the same code for PHP and HTTP.

## Resource Validation

Resource representations are validated using JsonSchema to maintain resource consistency. Using standard schemas for validation allows the use of external tools.

## Stream Output
* Streaming resource representations allows outputting large-scale content that cannot be handled in memory.
* Streams can be mixed with normal value assignments.

## Visualization and Debugging

* During development, resource scopes and tools are graphically displayed on HTML.
* Resource state can be checked on the web page, and PHP code and HTML templates can be edited online and reflected in real-time.

## Fast Bootstrap

* Pre-compilation generates PHP code for dependency generation to realize minimal bootstrapping.
* In an ideal DI world, instances are generated only once at startup. This is called the root object, and by caching this root object, initialization is reused to accelerate application startup.

## Integration of PHP Interfaces and SQL Execution
In BEAR.Sunday, SQL statement execution for interacting with databases can be easily managed using PHP interfaces. It is possible to bind SQL execution objects directly to interfaces without implementing classes. This improves code reusability and enhances modularity.

### Query Argument Evaluation
BEAR.Sunday interfaces can accept not only scalar values but also objects. In particular, how objects are evaluated by the interface is important. For example, when a DateTimeInterface object is passed to an interface, it is automatically evaluated to be properly handled as a date within the SQL statement. This allows efficient handling of date and time data.

### Dependency Injection of Query Arguments
In BEAR.Sunday, it is also possible to inject dependencies into interfaces. This allows dynamically supplying necessary objects and values to interfaces, enabling more flexible application design. Using dependency injection makes code testing easier and maintains high cohesion while keeping coupling low.

### AI and Tool-Assisted SQL Generation and Optimization
In BEAR.Sunday, it is also possible to inject dependencies into interfaces. This allows dynamically supplying necessary objects and values to interfaces, enabling more flexible application design. Using dependency injection makes code testing easier and maintains high cohesion while keeping coupling low.

### Comprehensive Debugging and Maintenance Convenience
Direct SQL management makes debugging easier when errors occur. SQL query behavior can be directly observed, allowing rapid problem identification and correction. Also, because queries can be directly modified and functions extended, application maintenance and evolution proceed smoothly.

* PHP interfaces and SQL can be prepared, and SQL execution objects can be bound to PHP interfaces without implementing classes.
* PHP interfaces can specify not only scalar values but also objects to be evaluated as strings. For example, specifying DateTimeInterface evaluates it as an SQL date.
* Dependencies can be injected as arguments into PHP interfaces.

## API Document Generation

API documentation is automatically generated from code. This maintains consistency between code and documentation and improves maintainability.

## Integration with Other Systems

* Integration with console applications allows access from both web and command line without changing source code.
* Different applications can be run concurrently within the same PHP runtime, and all resources can be accessed from an HTTP client.
* Local and remote BEAR.Sunday applications can be handled similarly, and BEAR.Thrift allows cooperation with applications in other languages.

## Standards Compliance

* JSON format and www-form format are supported by default, and resource requests are interpreted according to content type.
* Semantic versioning is adopted to maintain backward compatibility.
* Errors are returned in the `vnd.error+json` media type format by default, with error messages including error details.
* ETag is used when resource state changes to invalidate caches.
* When caching, HTTP headers such as `Cache-Control`, `Ages`, `Last-Modified`, and `ETag` are added to the HTTP headers.

## Object-Oriented Principles

BEAR.Sunday emphasizes object-oriented principles to make applications maintainable in the long term.

### Composition over Inheritance

It is recommended to use composition instead of inheritance. In general, directly calling parent class methods from a child class can potentially increase the coupling between classes. The only abstract class that requires inheritance at runtime for design purposes is the `BEAR\Resource\ResourceObject` resource class, but the methods of ResourceObject exist solely for other classes to use. There are no cases where a user calls "methods of a framework's parent class" at runtime in any class.

### Everything is Injected

Framework classes never refer to "configuration files" or "debug constants" at runtime to determine behavior. Dependencies are injected according to behavior. This means that to change application behavior, there is no need to change code, only to change the binding of dependency implementations to interfaces. APP_DEBUG and APP_MODE constants do not exist. There is no way to know which mode the software is running in after it has been launched, nor is there a need to know.

### Root Object

In the original world of DI, users avoid directly handling the injector (DI container) as much as possible. Instead, a single root object is generated at the application's entry point to start the application. In BEAR.Sunday's DI, there is virtually no DI container manipulation even at configuration time. The root object is huge, but because it is a single variable, it is reused across requests to realize an extremely optimized bootstrap.

## Non-Destructive Backward Compatibility

BEAR.Sunday is designed with an emphasis on maintaining backward compatibility in software evolution. In modern software development, the frequent breaking of backward compatibility and the associated burden of revisions and testing have become issues, but BEAR.Sunday aims to and has succeeded in avoiding this problem.

This does not mean stopping software evolution. The Web has been changing for decades, but its core parts have remained unchanged, and backward compatibility has been maintained. BEAR.Sunday is designed to apply this spirit of the Web to application frameworks as well.

BEAR.Sunday adopts semantic versioning to prevent the addition of new features and changes to existing features from affecting existing code. Obsolete and unused code is given the "deprecated" attribute but is never deleted and does not affect the behavior of existing code. Instead, new features are added, and evolution continues.

In fact, since its release in PHP 5.4, BEAR.Sunday has added many features, but existing applications continue to work without modification. Furthermore, with the use of static analysis tools and such that have evolved with the PHP ecosystem, the code has become cleaner and faster.

The design that makes backward compatibility an absolute imperative and the approach of semantic versioning enable this long-term compatibility. This allows developers to confidently adopt BEAR.Sunday and benefit from the evolving ecosystem.

## Code Quality

To provide applications with high code quality, the BEAR.Sunday framework itself maintains a high standard of code quality.

* The framework code is applied with both the static analysis tools psalm and phpstan at the maximum level.
* 100% test coverage is maintained.
* Type coverage is also nearly 100%. The use of mixed is minimized.
* It is a fundamentally immutable system, clean enough that initialization is not required every time even in testing. It unleashes the power of PHP's asynchronous communication engines like Swoole.
Loading

0 comments on commit 656a4f0

Please sign in to comment.