-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathllms-full.txt
More file actions
8537 lines (6163 loc) · 285 KB
/
llms-full.txt
File metadata and controls
8537 lines (6163 loc) · 285 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# BEAR.Sunday PHP Framework
> BEAR.Sunday is a resource-oriented PHP framework combining clean object-oriented design with REST principles. Built on Ray.Di (Dependency Injection), Ray.Aop (Aspect-Oriented Programming), and BEAR.Resource (REST Resources). Emphasizes standards compliance, longevity, and flexibility.
>
> Instead of a global MODE constant and conditionals, application behavior is determined by a context string (e.g. `prod-hal-api-app`). Each segment maps to a DI module whose bindings override earlier ones — no `if` branches on environment values. The context is used only at compile time to build the object graph; application code never knows what context it runs in.
## Getting Started
# What is BEAR.Sunday?
BEAR.Sunday is a PHP application framework that combines clean object-oriented design with a resource-oriented architecture aligned with the fundamental principles of the web. This framework emphasizes compliance with standards, a long-term perspective, high efficiency, flexibility, self-description, and importantly, simplicity.
## Framework
BEAR.Sunday consists of three frameworks.
`Ray.Di` interfaces object dependencies based on the [Principle of Dependency Inversion](http://en.wikipedia.org/wiki/Dependency_inversion_principle).
`Ray.Aop` connects core concerns and cross-cutting concerns with [aspect-oriented programming](http://en.wikipedia.org/wiki/Aspect-oriented_programming).
`BEAR.Resource` connects application data and functionality with resources with [REST constraints](https://en.wikipedia.org/wiki/Representational_state_transfer).
The framework provides constraints and design principles that guide the entire application, promoting consistent design and implementation, and resulting in high-quality, clean code.
## Libraries
Unlike full-stack frameworks, BEAR.Sunday does not include its own libraries for specific tasks like authentication or database management. Instead, it favors the use of high-quality third-party libraries.
This approach is based on two key design philosophies: firstly, the belief that "frameworks remain, libraries change," acknowledging that while the framework provides a stable foundation, libraries evolve to meet changing needs over time. Secondly, it empowers "application architects with the right and responsibility to choose libraries" that best fit their application's requirements, constraints, and goals.
BEAR.Sunday draws a clear distinction between frameworks and libraries, emphasizing the role of the framework as an application constraint.
## Architecture
BEAR.Sunday departs from the traditional MVC (Model-View-Controller) architecture, embracing a resource-oriented architecture (ROA). In this paradigm, data and business logic are unified as resources, and the design revolves around links and operations on those resources. While ROA is commonly used for REST API design, BEAR.Sunday extends it to the entire web application.
## Long-term perspective
BEAR.Sunday is designed with a long-term view, focusing on application maintainability:
- **Constraints**: The consistent application constraints imposed by DI, AOP, and REST remain unchanged over time.
- **Eternal 1.x**:The System That Never Breaks Backward Compatibility. Since its initial release in 2015, BEAR.Sunday has continuously evolved without introducing any backward-incompatible changes. This steadfast approach eliminates the need for compatibility fixes and their associated testing, thereby preventing future technical debt. The system remains cutting-edge, ensuring easy upgrades and access to the latest features without compatibility concerns.
- **Standards Compliance**: BEAR.Sunday adheres to various standards, including HTTP, JsonSchema, and others. For DI, it follows Google Guice, and for AOP, it aligns with the Java Aop Alliance.
## Connectivity
BEAR.Sunday transcends traditional web applications, offering seamless integration with a diverse range of clients:
- **HTTP Client**: All resources are directly accessible via HTTP, unlike models or controllers in MVC.
- **Console Access**:
Resources can be accessed directly from the console without changing the source code, allowing the same resources to be used from both web and command-line interfaces. Additionally, BEAR.CLI enables resources to be distributed as standalone UNIX commands through Homebrew.
- **composer package**: Resources from applications installed under the vendor directory via Composer can be invoked directly, enabling coordination between multiple applications without resorting to microservices.
- **Multilingual framework**: BEAR.Thrift facilitates seamless and efficient interoperability with other languages and PHP versions.
## Web Cache
By integrating resource-oriented architecture with modern CDN technology, we achieve distributed caching that surpasses traditional server-side TTL caching. BEAR.Sunday's design philosophy adheres to the fundamental principles of the Web, utilizing a CDN-centered distributed caching system to ensure high performance and availability.
- **Distributed Caching**: By caching on the client, CDN, and server-side, both CPU and network costs are minimized.
- **Identification**: ETag-based verification ensures that only modified content is retrieved, enhancing network efficiency.
- **Fault tolerance**: Event-based cache invalidation allows all content to be stored in CDN caches without TTL limitations. This improves fault tolerance to the point where the system remains available even if the PHP or database servers go down.
## Performance
BEAR.Sunday is designed with a focus on performance and efficiency while maintaining maximum flexibility. This approach enables a highly optimized bootstrap, positively impacting both user experience and system resources. Performance is always one of the primary concerns for BEAR.Sunday, playing a central role in our design and development decisions.
## Because Everything is a Resource
BEAR.Sunday embraces the essence of the Web, where "Everything is a Resource." As a PHP web application framework, it excels by providing superior constraints based on object-oriented and REST principles, applicable to the entire application.
These constraints encourage developers to design and implement consistently and improve the quality of the application in the long run. At the same time, the constraints provide developers with freedom and enhance creativity in building the application.
# Technology
The distinctive technologies and features of BEAR.Sunday are explained in the following chapters.
* [Architecture and Design Principles](#architecture-and-design-principles)
* [Performance and Scalability](#performance-and-scalability)
* [Developer Experience](#developer-experience)
* [Extensibility and Integration](#extensibility-and-integration)
* [Design Philosophy and Quality](#design-philosophy-and-quality)
* [The Value BEAR.Sunday Brings](#the-value-bearsunday-brings)
## Architecture and Design Principles
### Resource Oriented Architecture (ROA)
BEAR.Sunday's ROA is an architecture that realizes RESTful API within a web application. It is the core of BEAR.Sunday's design principles, functioning as both a hypermedia framework and a service-oriented architecture. Similar to the Web, all data and functions are considered resources and are operated through standardized interfaces such as GET, POST, PUT, and DELETE.
#### URI
URI (Uniform Resource Identifier) is a key element to the success of the Web and is also at the heart of BEAR.Sunday's ROA. By assigning URIs to all resources handled by the application, resources can be easily identified and accessed. URIs not only function as identifiers for resources but also express links between resources.
#### Uniform Interface
Access to resources is done using HTTP methods such as GET, POST, PUT, and DELETE. These methods specify the operations that can be performed on resources and provide a common interface regardless of the type of resource.
#### Hypermedia
In BEAR.Sunday's Resource Oriented Architecture (ROA), each resource provides affordances (available operations and functions for the client) through hyperlinks. These links represent the operations that clients can perform and guide navigation within the application.
#### Separation of State and Representation
In BEAR.Sunday's ROA, the state of a resource and its representation are clearly separated. The state of the resource is managed by the resource class, and the renderer injected into the resource converts the state of the resource into a resource state representation in various formats (JSON, HTML, etc.). Domain logic and presentation logic are loosely coupled, and even with the same code, changing the binding of the state representation based on the context will also change the representation.
#### Differences from MVC
BEAR.Sunday's ROA (Resource Oriented Architecture) takes a different approach from the traditional MVC architecture. MVC composes an application with three components: model, view, and controller. The controller receives a request object, controls a series of processes, and returns a response. In contrast, a resource in BEAR.Sunday, following the Single Responsibility Principle (SRP), only specifies the state of the resource in the request method and is not involved in the representation.
While there are no constraints on the relationship between controllers and models in MVC, resources have explicit constraints on including other resources using hyperlinks and URIs. This allows for declarative definition of content inclusion relationships and tree structures while maintaining information hiding of the called resources.
MVC controllers manually retrieve values from the request object, while resources declaratively define the required variables as arguments to the request method. Therefore, input validation is also performed declaratively using JsonSchema, and the arguments and their constraints are documented.
### Dependency Injection (DI)
Dependency Injection (DI) is an important technique for enhancing the design and structure of applications in object-oriented programming. The central purpose of DI is to divide an application's responsibilities into multiple components with independent domains or roles and manage the dependencies between them.
DI helps to horizontally divide one responsibility into multiple functions. The divided functions can be developed and tested independently as "dependencies". By injecting those dependencies with clear responsibilities and roles based on the single responsibility principle from the outside, the reusability and testability of objects are improved. Dependencies can also be vertically divided into other dependencies, forming a tree of dependencies.
BEAR.Sunday's DI uses a separate package called [Ray.Di](https://github.com/ray-di/Ray.Di), which adopts the design philosophy of Google's DI framework Guice and covers almost all of its features.
It also has the following characteristics:
* Bindings can be changed by context, allowing different implementations to be injected during testing.
* Attribute-based configuration enhances the self-descriptiveness of the code.
* Ray.Di performs dependency resolution at compile-time, improving runtime performance. This is different from other DI containers that resolve dependencies at runtime.
* Object dependencies can be visualized as a graph. Example: [Root Object](/images/app.svg).
<img src="https://ray-di.github.io/images/logo.svg" width="180" alt="Ray.Di logo">
### Aspect Oriented Programming (AOP)
Aspect-Oriented Programming (AOP) is a pattern that realizes flexible applications by separating essential concerns such as business logic from cross-cutting concerns such as logging and caching. Cross-cutting concerns refer to functions or processes that span across multiple modules or layers. It is possible to bind cross-cutting processes based on search conditions and flexibly configure them based on context.
BEAR.Sunday's AOP uses a separate package called Ray.Aop, which declaratively binds cross-cutting processes by attaching PHP attributes to classes and methods. Ray.Aop conforms to Java's [AOP Alliance](https://aopalliance.sourceforge.net/).
AOP is often misunderstood as a technology that "has the strong power to break the existing order". However, its raison d'être is not to exercise power beyond constraints but to complement areas where object-orientation is not well-suited, such as exploratory assignment of functions using matchers and separation of cross-cutting processes. AOP is a paradigm that can create cross-cutting constraints for applications, in other words, it functions as an application framework.
## Performance and Scalability
### ROA-based Event-Driven Content Strategy with Modern CDN Integration
BEAR.Sunday realizes an advanced event-driven caching strategy by integrating with instant purge-capable CDNs such as Fastly, with Resource Oriented Architecture (ROA) at its core. Instead of invalidating caches based on the conventional TTL (Time to Live), this strategy immediately invalidates the CDN and server-side caches, as well as ETags (entity tags), in response to resource state change events.
By taking this approach of creating non-volatile and persistent content on CDNs, it not only avoids SPOF (Single Point of Failure) and achieves high availability and fault tolerance but also maximizes user experience and cost efficiency. It realizes the same distributed caching as static content for dynamic content, which is the original principle of the Web. It re-realizes the scalable and network cost-reducing distributed caching principle that the Web has had since the 1990s with modern technology.
#### Cache Invalidation by Semantic Methods and Dependencies
In BEAR.Sunday's ROA, each resource operation is given a semantic role. For example, the GET method retrieves a resource, and the PUT method updates a resource. These methods collaborate in an event-driven manner and efficiently invalidate related caches. For instance, when a specific resource is updated, the cache of resources that require that resource is invalidated. This ensures data consistency and freshness, providing users with the latest information.
#### Identity Confirmation and Fast Response with ETag
By setting ETags before the system boots, content identity can be quickly confirmed, and if there are no changes, a 304 Not Modified response is returned to minimize network load.
#### Partial Updates with Donut Caching and ESI
BEAR.Sunday adopts a donut caching strategy and uses ESI (Edge Side Includes) to enable partial content updates at the CDN edge. This technology allows for dynamic updates of only the necessary parts without re-caching the entire page, improving caching efficiency.
In this way, BEAR.Sunday and Fastly's integration of ROA-based caching strategy not only realizes advanced distributed caching but also enhances application performance and fault tolerance.
### Accelerated Startup
In the original world of DI, users avoid dealing directly with the injector (DI container) as much as possible. Instead, they generate a single root object 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 is a single variable, so it is reused beyond requests, realizing an optimized bootstrap to the limit.
### Transparent Parallel Execution
In BEAR.Sunday, a URI expresses "intent" rather than being merely a communication protocol or locator. `query://self/user_profile` expresses only the intent "I want the user's profile information"—whether it comes from MySQL or Redis is hidden from the application.
This complete separation of "What" from "How" enables multiple resources embedded with `#[Embed]` to be fetched in parallel without changing any application code. Resource classes written 10 years ago can benefit from parallel execution just by adding a Module.
Three tiers of solutions are available based on server environment constraints: ext-parallel (thread pool), Swoole (coroutines), and mysqli (DB queries only). Whichever you choose, application code requires no changes. Develop and debug with standard PHP, then switch to parallel execution in production with just a configuration change.
## Developer Experience
### Ease of Testing
BEAR.Sunday allows for easy and effective testing due to the following design features:
* Each resource is independent, and testing is easy due to the stateless nature of REST requests.
Since the state and representation of resources are clearly separated, it is possible to test the state of resources even when they are in HTML representation.
* API testing can be performed while following hypermedia links, and tests can be written in the same code for PHP and HTTP.
* Different implementations are bound during testing through context-based binding.
### Application as Documentation
In BEAR.Sunday, the application itself is the documentation. Multiple documentation formats are automatically generated from code.
- **ApiDoc HTML**: Developer reference
- **OpenAPI 3.1**: Toolchain integration
- **JSON Schema**: Information model definition
- **llms.txt**: AI-readable application overview
When using an ALPS profile as the SSOT (Single Source of Truth), you define the application semantics (vocabulary, state transitions, operation meanings) first, then generate code from it. The same document holds different meanings for different readers—developers see endpoints, architects read state transitions, and AI extracts ontology.
### Visualization and Debugging
Utilizing the technical feature of resources rendering themselves, during development, the scope of resources can be indicated on HTML, resource states can be monitored, and PHP code and HTML templates can be edited in an online editor and reflected in real-time.
## Extensibility and Integration
### Integration of PHP Interfaces and SQL Execution
In BEAR.Sunday, the execution of SQL statements for interacting with databases can be easily managed through PHP interfaces. It is possible to directly bind SQL execution objects to PHP interfaces without implementing classes. The boundary between the domain and infrastructure is connected by PHP interfaces.
In that case, types can also be specified for arguments, and any missing parts are dependency-resolved by DI and used as strings. Even when the current time is needed for SQL execution, there is no need to pass it; it is automatically bound. This helps keep the code concise as the client is not responsible for passing all arguments.
Moreover, direct management of SQL makes debugging easier when errors occur. The behavior of SQL queries can be directly observed, allowing for quick identification and correction of problems.
### Integration with Other Systems
BEAR.Sunday resources can be accessed through various interfaces. In addition to web interfaces, resources can be accessed directly from the console, allowing the same resources to be used from both web and command-line interfaces without changing the source code. Furthermore, using BEAR.CLI, resources can be distributed as standalone UNIX commands. Multiple BEAR.Sunday applications can also run concurrently within the same PHP runtime, enabling collaboration between independent applications without building microservices.
### Stream Output
By assigning streams such as file pointers to the body of a resource, large-scale content that cannot be handled in memory can be output. In that case, streams can also be mixed with ordinary variables, allowing flexible output of large-scale responses.
### Gradual Migration from Other Systems
BEAR.Sunday provides a gradual migration path and enables seamless integration with other frameworks and systems such as Laravel and Symfony. This framework can be implemented as a Composer package, allowing developers to gradually introduce BEAR.Sunday's features into their existing codebase.
### Flexibility in Technology Migration
BEAR.Sunday protects investments in preparation for future technological changes and evolving requirements. Even if there is a need to migrate from this framework to another framework or language, the constructed resources will not go to waste. In a PHP environment, BEAR.Sunday applications can be integrated as Composer packages and continuously utilized, and BEAR.Thrift allows efficient access to BEAR.Sunday resources from other languages. When not using Thrift, access via HTTP is also possible. SQL code can also be easily reused.
Even if the library being used is strongly dependent on a specific PHP version, different versions of PHP can coexist using BEAR.Thrift.
## Design Philosophy and Quality
### Adoption of Standard Technologies and Elimination of Proprietary Standards
BEAR.Sunday has a design philosophy of adopting standard technologies as much as possible and eliminating framework-specific standards and rules. For example, it supports content negotiation for JSON format and www-form format HTTP requests by default and uses the [vnd.error+json](https://github.com/blongden/vnd.error) media type format for error responses. It actively incorporates standard technologies and specifications such as adopting [HAL](https://datatracker.ietf.org/doc/html/draft-kelly-json-hal) (Hypertext Application Language) for links between resources and using [JsonSchema](https://json-schema.org/) for validation.
On the other hand, it eliminates proprietary validation rules and framework-specific standards and rules as much as possible.
### Object-Oriented Principles
BEAR.Sunday emphasizes object-oriented principles to make applications maintainable in the long term.
#### Composition over Inheritance
Composition is recommended over inheritance classes. Generally, directly calling a parent class's method from a child class can potentially increase the coupling between classes. The only abstract class that requires inheritance at runtime by design is the resource class `BEAR\Resource\ResourceObject`, but the methods of ResourceObject exist solely for other classes to use. There is no case in BEAR.Sunday where a user calls a method of a framework's parent class that they have inherited at runtime.
#### Everything is Injected
Framework classes do not refer to "configuration files" or "debug constants" during execution to determine their behavior. Dependencies corresponding to the behavior are injected. This means that to change the application's behavior, there is no need to change the code; only the binding of the implementation of the dependency to the interface needs to be changed. Constants like APP_DEBUG or APP_MODE do not exist. There is no way to know in what mode the software is currently running after it has started, and there is no need to know.
### Permanent Assurance of Backward Compatibility
BEAR.Sunday is designed with an emphasis on maintaining backward compatibility in the evolution of software and has continued to evolve without breaking backward compatibility since its release. In modern software development, frequent breaking of backward compatibility and the associated burden of modification and testing have become a challenge, but BEAR.Sunday has avoided this problem.
BEAR.Sunday not only adopts semantic versioning but also does not perform major version upgrades that involve breaking changes. It prevents new feature additions or changes to existing features from affecting existing code. Code that has become old and unused is given the attribute "deprecated" but is never deleted and does not affect the behavior of existing code. Instead, new features are added, and evolution continues.
Here's the English translation of the revised text:
### Acyclic Dependencies Principle (ADP)
The Acyclic Dependencies Principle states that dependencies should be unidirectional and non-circular. The BEAR.Sunday framework adheres to this principle and is composed of a series of packages with a hierarchical structure where larger framework packages depend on smaller framework packages. Each level does not need to be aware of the existence of other levels that encompass it, and the dependencies are unidirectional and do not form cycles. For example, Ray.Aop is not even aware of the existence of Ray.Di, and Ray.Di is not aware of the existence of BEAR.Sunday.
<img src="/images/screen/package_adp.png" width="360px" alt="Framework structure following the Acyclic Dependencies Principle">
As backward compatibility is maintained, each package can be updated independently. Moreover, there is no version number that locks the entire system, as seen in other frameworks, and there is no mechanism for object proxies that hold cross-cutting dependencies between objects.
The Acyclic Dependencies Principle is in harmony with the DI (Dependency Injection) principle, and the root object generated during the bootstrapping process of BEAR.Sunday is also constructed following the structure of this Acyclic Dependencies Principle.
[<img src="/images/screen/clean-architecture.png" width="40%">](/images/screen/clean-architecture.png)
The same applies to the runtime. When accessing a resource, first, the cross-cutting processing of the AOP aspects bound to the method is executed, and then the method determines the state of the resource. At this point, the method is not aware of the existence of the aspects bound to it. The same goes for resources embedded in the resource's state. They do not have knowledge of the outer layers or elements. The separation of concerns is clearly defined.
### Code Quality
To provide applications with high code quality, the BEAR.Sunday framework also strives to maintain a high standard of code quality.
* The framework code is applied at the strictest level by both static analysis tools, Psalm and PHPStan.
* It maintains 100% test coverage and nearly 100% type coverage.
* It is fundamentally an immutable system and is so clean that initialization is not required every time, even in tests. It unleashes the power of PHP's asynchronous communication engines like Swoole.
### Architecture-Enabled Security Analysis
BEAR.Sunday's architecture fundamentally simplifies security analysis.
Every endpoint is a ResourceObject with explicit `onGet` and `onPost` methods, inputs are declared via JSON Schema, and dependencies are explicit through constructor injection. With no hidden magic or global state, static analysis tools can trace complete data flows.
This declarative architecture enables multi-layered security scanning combining SAST (static analysis), DAST (dynamic testing), taint analysis, and AI auditing. Framework-aware specialized tools detect vulnerabilities that generic tools cannot find.
## The Value BEAR.Sunday Brings
### Value for Developers
* Improved productivity: Based on robust design patterns and principles with constraints that don't change over time, developers can focus on core business logic.
* Collaboration in teams: By providing development teams with consistent guidelines and structure, it keeps the code of different engineers loosely coupled and unified, improving code readability and maintainability.
* Flexibility and extensibility: BEAR.Sunday's policy of not including libraries brings developers flexibility and freedom in component selection.
* Ease of testing: BEAR.Sunday's DI (Dependency Injection) and ROA (Resource Oriented Architecture) increase the ease of testing.
### Value for Users
* High performance: BEAR.Sunday's optimized fast startup and CDN-centric caching strategy brings users a fast and responsive experience.
* Reliability and availability: BEAR.Sunday's CDN-centric caching strategy minimizes single points of failure (SPOF), allowing users to enjoy stable services.
* Ease of use: BEAR.Sunday's excellent connectivity makes it easy to collaborate with other languages and systems.
### Value for Business
* Reduced development costs: The consistent guidelines and structure provided by BEAR.Sunday promote a sustainable and efficient development process, reducing development costs.
* Reduced maintenance costs: BEAR.Sunday's approach to maintaining backward compatibility increases technical continuity and minimizes the time and cost of change response.
* High extensibility: With technologies like DI (Dependency Injection) and AOP (Aspect Oriented Programming) that change behavior while minimizing code changes, BEAR.Sunday allows applications to be easily extended in line with business growth and changes.
* Excellent User Experience (UX): BEAR.Sunday provides high performance and high availability, increasing user satisfaction, enhancing customer loyalty, expanding the customer base, and contributing to business success.
Excellent constraints do not change. The constraints brought by BEAR.Sunday provide specific value to developers, users, and businesses respectively.
BEAR.Sunday is a framework designed based on the principles and spirit of the Web, providing developers with clear constraints to empower them to build flexible and robust applications.
# Version
## Supported PHP
[](https://github.com/bearsunday/BEAR.SupportedVersions/actions/workflows/continuous-integration.yml)
BEAR.Sunday supports the following supported PHP versions
* `8.1` (Old stable 25 Nov 2021 - 31 Dec 2025)
* `8.2` (Old stable 8 Dec 2022 - 31 Dec 2026)
* `8.3` (Old stable 23 Nov 2023 - 31 Dec 2027)
* `8.4` (Current stable 21 Nov 2024 - 31 Dec 2028)
* End of life ([EOL](http://php.net/eol.php))
* `5.5` (21 Jul 2016)
* `5.6` (31 Dec 2018)
* `7.0` (3 Dec 2018)
* `7.1` (1 Dec 2019)
* `7.2` (30 Nov 2020)
* `7.3` (6 Dec 2021)
* `7.4` (28 Nov 2022)
* `8.0` (26 Nov 2023)
The new optional package will be developed based on the current stable PHP. We encourage you to use the current stable PHP for quality, performance and security.
[BEAR.SupportedVersions](https://github.com/bearsunday/BEAR.SupportedVersions/), you can check the tests for each version in CI.
## Semver
BEAR.Sunday follows [Semantic Versioning](http://semver.org/lang/en/). It is not necessary to modify the application code on minor version upgrades.
`composer update` can be done at any time for packages.
## Version Policy
* The core package of the framework does not make a breaking change which requires change of user code.
* Since it does not do destructive change, it handles unnecessary old ones as `deprecated` but does not delete and new functions are always "added".
* When PHP comes to an EOL and upgraded to a major version (ex. `5.6` →` 7.0`), BEAR.Sunday will not break the BC of the application code. Even though the version number of PHP that is necessary to use the new module becomes higher, changes to the application codes are not needed.
BEAR.Sunday emphasizes clean code and **longevity**.
## Package version
The version of the framework does not lock the version of the library. The library can be updated regardless of the version of the framework.
# Quick Start
Installation is done via [composer](http://getcomposer.org)
```bash
VENDOR=MyVendor PACKAGE=MyProject composer create-project bear/skeleton my-project
cd my-project
```
Use `VENDOR` to specify the vendor name and `PACKAGE` to specify the package name for installation. If not specified, you will be prompted interactively.
Next, let's create a new resource. A resource is a class which corresponds, for instance, to a JSON payload (if working with an API-first driven model)
or a web page.
Create your own basic page resource in `src/Resource/Page/Hello.php`
```php
<?php
namespace MyVendor\MyProject\Resource\Page;
use BEAR\Resource\ResourceObject;
class Hello extends ResourceObject
{
public function onGet(string $name = 'BEAR.Sunday'): static
{
$this->body = [
'greeting' => 'Hello ' . $name
];
return $this;
}
}
```
In the above example, when the page is requested using a GET method, `Hello` and the `$name` parameter (which corresponds to `$_GET['name']`) are joined, and assigned to a variable `greeting`.
The BEAR.Sunday application that you have created will work on a web server, but also in the console.
```bash
php bin/page.php get /hello
php bin/page.php get '/hello?name=World'
```
```bash
200 OK
Content-Type: application/hal+json
{
"greeting": "Hello World",
"_links": {
"self": {
"href": "/hello?name=World"
}
}
}
```
Let us fire up the php server and access our page at [http://127.0.0.1:8080/hello](http://127.0.0.1:8080/hello).
```bash
php -S 127.0.0.1:8080 -t public
```
```bash
curl -i 127.0.0.1:8080/hello
```
## Core Concepts
# Package
BEAR.Sunday application is a composer package taking BEAR.Sunday framework as dependency package.
You can also install another BEAR.Sunday application package as dependency.
## Application organization
The file layout of the BEAR.Sunday application conforms to [php-pds/skeleton](https://github.com/php-pds/skeleton) standard.
### Invoke sequence
1. Console input (`bin/app.php`, `bin/page.php`) or the web entry file (`public/index.php`) executes the `bootstrap.php` function.
2. The `$app` application object is created for the given `$context` in `bootstrap.php`.
3. The router in `$app` converts the external resource request to an internal resource request.
4. The resource request is invoked, and the resulting representation is transferred to the client.
### bootstrap/
You can access same resource through console input or web access with same boot file.
```bash
php bin/app.php options /todos // console API access (app resource)
```
```bash
php bin/page.php get '/todos?id=1' // console Web access (page resource)
```
```bash
php -S 127.0.0.1bin/app.php // PHP server
```
You can create your own boot file for different context.
### bin/
Place command-line executable files.
### src/
Place application class file.
### public/
Web public folder.
### var/
`log` and `tmp` folder need write permission.
## Framework Package
### ray/aop
[](https://scrutinizer-ci.com/g/ray-di/Ray.Aop/)
[](https://codecov.io/gh/ray-di/Ray.Aop)
[](https://shepherd.dev/github/ray-di/Ray.Aop)
[](https://github.com/ray-di/Ray.Aop/actions/workflows/continuous-integration.yml)
An aspect oriented framework based on Java AOP Alliance API.
### ray/di
[](https://scrutinizer-ci.com/g/ray-di/Ray.Di/)
[](https://codecov.io/gh/ray-di/Ray.Di)
[](https://shepherd.dev/github/ray-di/Ray.Di)
[](https://github.com/ray-di/Ray.Di/actions/workflows/continuous-integration.yml)
A Google Guice style DI framework. It contains `ray/aop`.
### bear/resource
[](https://scrutinizer-ci.com/g/bearsunday/BEAR.Resource/?branch=1.x)
[](https://codecov.io/gh/bearsunday/BEAR.Resource)
[](https://shepherd.dev/github/bearsunday/BEAR.Resource)
[](https://github.com/bearsunday/BEAR.Resource/actions/workflows/continuous-integration.yml)
A REST framework for PHP object as a service. It contains `ray/di`.
### bear/sunday
[](https://scrutinizer-ci.com/g/bearsunday/BEAR.Sunday/?branch=1.x)
[](https://codecov.io/gh/bearsunday/BEAR.Sunday)
[](https://shepherd.dev/github/bearsunday/BEAR.Sunday)
[](https://github.com/bearsunday/BEAR.Sunday/actions/workflows/continuous-integration.yml)
A web application interface package. It contains `bear/resource`.
### bear/package
[](https://scrutinizer-ci.com/g/bearsunday/BEAR.Package/?branch=1.x)
[](https://codecov.io/gh/bearsunday/BEAR.Pacakge)
[](https://shepherd.dev/github/bearsunday/BEAR.Package)
[](https://github.com/bearsunday/BEAR.Package/actions/workflows/continuous-integration.yml)
A web application implmentation package. It contains `bear/sunday`.
## Library Package
Optional library package can be installed with `composer require` command.
| **Category** | **Composer package** | **Library**
| Router |
| |[bear/aura-router-module](https://github.com/bearsunday/BEAR.AuraRouterModule) | [Aura.Router v2](https://github.com/auraphp/Aura.Router/tree/2.x) |
| Database |
|| [ray/media-query](https://github.com/ray-di/Ray.MediaQuery) |
|| [ray/aura-sql-module](https://github.com/ray-di/Ray.AuraSqlModule) | [Aura.Sql v2](https://github.com/auraphp/Aura.Sql/tree/2.x)
|| [ray/dbal-module](https://github.com/ray-di/Ray.DbalModule) | [Doctrine DBAL](https://github.com/doctrine/dbal)
|| [ray/cake-database-module](https://github.com/ray-di/Ray.CakeDbModule) | [CakePHP v3 database](https://github.com/cakephp/database)
|| [ray/doctrine-orm-module](https://github.com/kawanamiyuu/Ray.DoctrineOrmModule) | [Doctrine ORM](https://github.com/doctrine/doctrine2)
| Storage |
||[bear/query-repository](https://github.com/bearsunday/BEAR.QueryRepository) | CQRS inspired repository
||[bear/query-module](https://github.com/ray-di/Ray.QueryModule) | Separation of external access such as DB or Web API
| Web
| |[madapaja/twig-module](http://bearsunday.github.io/manuals/1.0/ja/html.html) | [Twig](http://twig.sensiolabs.org/)
| |[ray/web-form-module](http://bearsunday.github.io/manuals/1.0/ja/form.html) | Web form
| |[ray/aura-web-module](https://github.com/Ray-Di/Ray.AuraWebModule) | [Aura.Web](https://github.com/auraphp/Aura.Web)
| |[ray/aura-session-module](https://github.com/ray-di/Ray.AuraSessionModule) | [Aura.Session](https://github.com/auraphp/Aura.Session)
| |[ray/symfony-session-module](https://github.com/kawanamiyuu/Ray.SymfonySessionModule) | [Symfony Session](https://github.com/symfony/http-foundation/tree/master/Session)
| Validation |
| |[ray/validate-module](https://github.com/ray-di/Ray.ValidateModule) | [Aura.Filter](https://github.com/auraphp/Aura.Filter)
| |[satomif/extra-aura-filter-module](https://github.com/satomif/ExtraAuraFilterModule)| [Aura.Filter](https://github.com/auraphp/Aura.Filter)
| Authorization and Authentication
| |[ray/oauth-module](https://github.com/Ray-Di/Ray.OAuthModule) | OAuth
| |[kuma-guy/jwt-auth-module](https://github.com/kuma-guy/BEAR.JwtAuthModule) | JSON Web Token
| |[ray/role-module](https://github.com/ray-di/Ray.RoleModule) | Zend Acl
| |[bear/acl-resource](https://github.com/bearsunday/BEAR.AclResource) | ACL based embedded resource
| Hypermedia
| |[kuma-guy/siren-module](https://github.com/kuma-guy/BEAR.SirenModule) | Siren
| Development
| |[ray/test-double](https://github.com/ray-di/Ray.TestDouble) | Test Double
| Asynchronous high performance |
| |[MyVendor.Swoole](https://github.com/bearsunday/MyVendor.Swoole) | [Swoole](https://github.com/swoole/swoole-src)
## Vendor Package
You can reuse common packages and tool combinations as modules with only modules and share modules of similar projects.[^1]
## Semver
All packages adhere to [Semantic Versioning](http://semver.org/).
---
[^1]: See [Koriym.DbAppPackage](https://github.com/koriym/Koriym.DbAppPackage)
# <a name="app"></a>Application
## Sequence
A BEAR.Sunday app has a run order of `compile`, `request` and `response`.
### 0. Compile
An `$app` application object is created through `DI` and `AOP` configuration depending on a specified context.
An `$app` is made up of service objects as it's properties that are needed to run the application such as a `router` or `transfer` etc.
`$app` then connects these object together depending on whether it is owned by another or contains other objects.
This is called an [Object Graph](http://en.wikipedia.org/wiki/Object_graph).
`$app` is then serialized and reused in each request and response.
* router - Converting external input to resource requests
* resource - Resource client
* transfer - Output
### 1. Request
An application resource request and resource object is created based on the HTTP request.
A resource object which has methods that respond to `onGet`, `onPost` etc upon request sets the `code` or `body` property of it's own resource state.
The resource object can then `#[Embed]` or `#[Link]` other resource objects.
Methods on the resource object are only for changing the resources state and have no interest in the representation itself (HTML, JSON etc).
Before and after the method, application logic bound to the method, such as logging and authentication, is executed in AOP.
### 2. Response
A `Renderer` is injected into the resource object, then the state of resource is represented as HTML, JSON etc or however it has been configured, it is then transfered to the client.
<img src="/images/screen/diagram.png" style="max-width: 100%;height: auto;"/>
## Boot File
To run an application, we need just two lines of code.
An entry point for a web server or console application access is usually set to `public/index.php` or `bin/app.php`.
As you can see below, we need to pass an application context to `bootstrap.php` the application script.
```php
<?php
require dirname(__DIR__) . '/autoload.php';
exit((require dirname(__DIR__) . '/bootstrap.php')('prod-html-app'));
```
Depending on your context choose a boot file.
```bash
// fire php server
php -S 127.0.0.1:8080 public/index.php
```
```
// console access
php bin/app.php get /user/1
```
## Context
The composition of the application object `$app` changes in response to the defined context, so that application behavior changes.
Depending on the defined context the building of the application object `$app` changes, altering the overall behavior.
For example, `WebRouter` is bound to `RouterInterface` by default.
However, if `Cli` mode is set (instead of HTTP) the `CliRouter` is bound to the `RouterInterface` and it will then take console input.
There are built-in and custom contexts that can be used in an application.
### Built-in Contexts
* `api` API Application
* `cli` Console Application
* `hal` HAL Application
* `prod` Production
For `app`, resources are rendered in JSON.
`api` changes the default resource schema from page to app; web root access (GET /) is from page://self/ to app://self/.
Set `cli` to be a console application.
prod` makes it a production application with cache settings, etc.
You can also use a combination of these built-in contexts and add your own custom contexts.
If you set the context to `prod-hal-api-app` your application will run as an API application in production mode using the [HAL](http://stateless.co/hal_specification.html) media type.
### Custom Context
Place it in `src/Module`/ of the application; if it has the same name as the builtin context, the custom context will take precedence. You can override some of the constraints by calling the built-in context from the custom context.
Each application context (cli, app etc) represents a module.
For example the `cli` context relates to a `CliModule`, then binds all of the DI and AOP bindings that is needed for a console application.
### Context Agnostic
The context value is used only to create the root object and then disappears. There is no global "mode" that can be referenced by the application, and the application can not know what context it is currently running in. The behavior should only change through **code that is dependent on an interface**[^dip] and changes of dependencies by context.
---
[^dip]: [Dependency inversion principle](https://en.wikipedia.org/wiki/Dependency_inversion_principle)
# Modules
A Module is a collection of DI & AOP bindings that sets up your application.
BEAR.Sunday doesn't have a *global* config file or a config class to set default values for components such as a database or a template engine.
Instead for each peice of functionality we set up DI and AOP by injecting configuration values into a stand alone module.
`AppModule` (src/Module/AppModule.php) is the root module. We use an `install()` method in here to load each module that we would like to invoke.
You can also override existing bindings by using `override()`.
```php?start_inline
class AppModule extends AbstractAppModule
{
/**
* {@inheritdoc}
*/
protected function configure()
{
// ...
// install additional modules
$this->install(new AuraSqlModule('mysql:host=localhost;dbname=test', 'username', 'password');
$this->install(new TwigModule));
// install basic module
$this->install(new PackageModule));
}
}
```
## DI bindings
`Ray.Di` is the core DI framework used in BEAR.Sunday. It binds interfaces to a class or factory to create an object graph.
```php?start_inline
// Class binding
$this->bind($interface)->to($class);
// Provider (factory) binding
$this->bind($interface)->toProvider($provider);
// Instance binding
$this->bind($interface)->toInstance($instance);
// Named binding
$this->bind($interface)->annotatedWith($annotation)->to($class);
// Singleton
$this->bind($interface)->to($class)->in(Scope::SINGLETON);
// Constructor binding
$this->bind($interface)->toConstructor($class, $named);
```
More info can be found at Ray.Di [README](https://github.com/ray-di/Ray.Di/blob/2.x/README.md)
### Binding Priority
#### Within a Single Module
Bindings declared first take priority. In the following example, `Foo1` takes priority:
```php?start_inline
$this->bind(FooInterface::class)->to(Foo1::class);
$this->bind(FooInterface::class)->to(Foo2::class);
```
#### Module Installation Priority
Modules installed first take priority. In the following example, `Foo1Module` takes priority:
```php?start_inline
$this->install(new Foo1Module);
$this->install(new Foo2Module);
```
To give a later module priority, use `override()`. In the following example, `Foo2Module` takes priority:
```php?start_inline
$this->install(new Foo1Module);
$this->override(new Foo2Module);
```
#### Context String Priority
Context modules are processed in **reverse order** (right-to-left). For example, with context `prod-hal-api-app`:
```text
Installation order: AppModule → ApiModule → HalModule → ProdModule
```
Later installed modules can override earlier bindings. This means:
- `HalModule` takes priority over `AppModule`
- `ProdModule` takes priority over `HalModule`
When creating a custom context module that needs to override bindings from a built-in context (like `HalModule`), position it to the left of that context in the context string. For example, to override `HalModule`'s `RenderInterface` binding:
```php?start_inline
// Context: "prod-mycontext-hal-api-app"
// Installation order: AppModule → ApiModule → HalModule → MycontextModule → ProdModule
```
## AOP Bindings
We can "search" for classes and methods with a built-in `Matcher`, then interceptors can be bound to any found methods.
```php?start_inline
$this->bindInterceptor(
// In any class
$this->matcher->any(),
// Method(s) names that start with "delete"
$this->matcher->startWith('delete'),
// Bind a Logger interceptor
[LoggerInterceptor::class]
);
$this->bindInterceptor(
// The AdminPage class or a class inherited from it.
$this->matcher->SubclassesOf(AdminPage::class),
// Annotated with the @Auth annotation
$this->matcher->annotatedWith(Auth::class),
// Bind the AdminAuthenticationInterceptor
[AdminAuthenticationInterceptor::class]
);
```
`Matcher` has various binding methods.
* [Matcher::any](https://github.com/ray-di/Ray.Aop/blob/develop-2/src/MatcherInterface.php#L16) - Any
* [Matcher::annotatedWith](https://github.com/ray-di/Ray.Aop/blob/develop-2/src/MatcherInterface.php#L23) - Annotation
* [Matcher::subclassesOf](https://github.com/ray-di/Ray.Aop/blob/2.x/src/MatcherInterface.php#L30) - Sub class
* [Matcher::startsWith](https://github.com/ray-di/Ray.Aop/blob/2.x/src/MatcherInterface.php#L37) - start with name (class or method)
* [Matcher::logicalOr](https://github.com/ray-di/Ray.Aop/blob/2.x/src/MatcherInterface.php#L44) - OR
* [Matcher::logicalAnd](https://github.com/ray-di/Ray.Aop/blob/2.x/src/MatcherInterface.php#L51) - AND
* [Matcher::logicalNot](https://github.com/ray-di/Ray.Aop/blob/2.x/src/MatcherInterface.php#L58) - NOT
## Interceptor
In an interceptor a `MethodInvocation` object gets passed to the `invoke` method. We can the decorate the targetted instances so that you run computations before or after any methods on the target are invoked.
```php?start_inline
class MyInterceptor implements MethodInterceptor
{
public function invoke(MethodInvocation $invocation)
{
// Before invocation
// ...
// Method invocation
$result = $invocation->proceed();
// After invocation
// ...
return $result;
}
}
```
With the `MethodInvocation` object, you can access the target method's invocation object, method's and parameters.
* [MethodInvocation::proceed](https://github.com/ray-di/Ray.Aop/blob/develop-2/src/Joinpoint.php#L39) - Invoke method
* [MethodInvocation::getMethod](https://github.com/ray-di/Ray.Aop/blob/develop-2/src/MethodInvocation.php) - Get method reflection
* [MethodInvocation::getThis](https://github.com/ray-di/Ray.Aop/blob/develop-2/src/Joinpoint.php#L48) - Get object
* [MethodInvocation::getArguments](https://github.com/ray-di/Ray.Aop/blob/develop-2/src/Invocation.php) - Get parameters
Annotations can be obtained using the reflection API.
```php?start_inline
$method = $invocation->getMethod();
$class = $invocation->getMethod()->getDeclaringClass();
```
* `$method->getAnnotations()`
* `$method->getAnnotation($name)`
* `$class->getAnnotations()`
* `$class->getAnnotation($name)`
## Environment Settings
BEAR.Sunday does not have any special environment mode except `prod`.
A Module and the application itself are unaware of the current environment.
There is no way to get the current "mode", this is intentional to keep the code clean.
# DI
Dependency injection is basically providing the objects that an object needs (its dependencies) instead of having it construct them itself.
With dependency injection, objects accept dependencies in their constructors. To construct an object, you first build its dependencies. But to build each dependency, you need its dependencies, and so on. So when you build an object, you really need to build an object graph.
Building object graphs by hand is labour intensive, error prone, and makes testing difficult. Instead, **Dependency Injector** ([Ray.Di](https://github.com/ray-di/Ray.Di)) can build the object graph for you.
| What is object graph ?
| Object-oriented applications contain complex webs of interrelated objects. Objects are linked to each other by one object either owning or containing another object or holding a reference to another object. This web of objects is called an object graph and it is the more abstract structure that can be used in discussing an application's state. - [Wikipedia](http://en.wikipedia.org/wiki/Object_graph)
Ray.Di is the core DI framework used in BEAR.Sunday, which is heavily inspired by Google [Guice](http://code.google.com/p/google-guice/wiki/Motivation?tm=6) DI framework.See more detail at [Ray.Di Manual](https://ray-di.github.io/manuals/1.0/en/index.html).
# AOP
BEAR.Sunday **AOP** enables you to write code that is executed each time a matching method is invoked. It's suited for cross cutting concerns ("aspects"), such as transactions, security and logging. Because interceptors divide a problem into aspects rather than objects, their use is called Aspect Oriented Programming (AOP).
The method interceptor API implemented is a part of a public specification called [AOP Alliance](http://aopalliance.sourceforge.net/).
## Interceptor
[MethodInterceptors](https://github.com/ray-di/Ray.Aop/blob/2.x/src/MethodInterceptor.php) are executed whenever a matching method is invoked.
They have the opportunity to inspect the call: the method, its arguments, and the receiving instance.
They can perform their cross-cutting logic and then delegate to the underlying method.
Finally, they may inspect the return value or the exception and return. Since interceptors may be applied to many methods and will receive many calls, their implementation should be efficient and unintrusive.
```php
use Ray\Aop\MethodInterceptor;
use Ray\Aop\MethodInvocation;
class MyInterceptor implements MethodInterceptor
{
public function invoke(MethodInvocation $invocation)
{
// Process before method invocation
// ...
// Original method invocation
$result = $invocation->proceed();
// Process after method invocation
// ...
return $result;
}
}
```
## Bindings
"Find" the target class and method with `Matcher` and bind the interceptor to the matching method in [Module](module.html).
```php
$this->bindInterceptor(
$this->matcher->any(), // In any class,
$this->matcher->startsWith('delete'), // Method(s) names that start with "delete",
[Logger::class] // Bind a Logger interceptor
);
$this->bindInterceptor(
$this->matcher->subclassesOf(AdminPage::class), // Of the AdminPage class or a class inherited from it
$this->matcher->annotatedWith(Auth::class), // Annotated method with the @Auth annotation
[AdminAuthentication::class] //Bind the AdminAuthenticationInterceptor
);
```
There are various matchers.
* [Matcher::any](https://github.com/ray-di/Ray.Aop/blob/develop-2/src/MatcherInterface.php#L16)
* [Matcher::annotatedWith](https://github.com/ray-di/Ray.Aop/blob/develop-2/src/MatcherInterface.php#L23)
* [Matcher::subclassesOf](https://github.com/ray-di/Ray.Aop/blob/develop-2/src/MatcherInterface.php#L30)
* [Matcher::startsWith](https://github.com/ray-di/Ray.Aop/blob/develop-2/src/MatcherInterface.php#L37)
* [Matcher::logicalOr](https://github.com/ray-di/Ray.Aop/blob/develop-2/src/MatcherInterface.php#L44)
* [Matcher::logicalAnd](https://github.com/ray-di/Ray.Aop/blob/develop-2/src/MatcherInterface.php#L51)
* [Matcher::logicalNot](https://github.com/ray-di/Ray.Aop/blob/develop-2/src/MatcherInterface.php#L58)
```
With the `MethodInvocation` object, you can access the target method's invocation object, method's and parameters.
* [MethodInvocation::proceed](https://github.com/ray-di/Ray.Aop/blob/develop-2/src/Joinpoint.php#L39) - Invoke method
* [MethodInvocation::getMethod](https://github.com/ray-di/Ray.Aop/blob/develop-2/src/MethodInvocation.php) - Get method reflection
* [MethodInvocation::getThis](https://github.com/ray-di/Ray.Aop/blob/develop-2/src/Joinpoint.php#L48) - Get object
* [MethodInvocation::getArguments](https://github.com/ray-di/Ray.Aop/blob/develop-2/src/Invocation.php) - Pet parameters
Annotations can be obtained using the reflection API.
```php
$method = $invocation->getMethod();
$class = $invocation->getMethod()->getDeclaringClass();
```
* `$method->getAnnotations()` // get method annotations
* `$method->getAnnotation($name)`
* `$class->getAnnotations()` // get class annotations
* `$class->getAnnotation($name)`
## Own matcher
You can have your own matcher.
To create `contains` matcher, You need to provide a class which has two methods. One is `matchesClass` for a class match.
The other one is `matchesMethod` method match. Both return the boolean result of match.
```php
use Ray\Aop\AbstractMatcher;
class ContainsMatcher extends AbstractMatcher
{
/**
* {@inheritdoc}
*/
public function matchesClass(\ReflectionClass $class, array $arguments) : bool
{
list($contains) = $arguments;
return (strpos($class->name, $contains) !== false);
}
/**
* {@inheritdoc}
*/
public function matchesMethod(\ReflectionMethod $method, array $arguments) : bool
{
list($contains) = $arguments;
return (strpos($method->name, $contains) !== false);
}
}
```
Module
```php