diff --git a/manuals/1.0/en/06-semantic-variables.md b/manuals/1.0/en/06-semantic-variables.md index cb07461..b606b72 100644 --- a/manuals/1.0/en/06-semantic-variables.md +++ b/manuals/1.0/en/06-semantic-variables.md @@ -226,16 +226,29 @@ Semantic Variables make **impossible states impossible**. Invalid email addresse The type system itself becomes a **domain language**, where each type speaks of what can exist in your business domain. -Looking at function signatures, they become specifications: +## Design by Contract + +Constructor arguments reveal preconditions. Properties reveal postconditions: ```php -function processOrder(ProductCode $product, PaymentAmount $amount, CustomerAge $age) +final class ProcessedOrder { - // The signature IS the specification + public function __construct( + #[Input] #[Verified] string $productCode, // Precondition: verified product code + #[Input] int $paymentAmount, // Precondition: payment amount + #[Input] #[Adult] int $age // Precondition: adult age + ) { + // Can only exist when preconditions are satisfied + $this->orderNumber = $this->generateOrderNumber(); + $this->processedAt = new DateTime(); + } + + public readonly string $orderNumber; // Postcondition: order number always exists + public readonly DateTime $processedAt; // Postcondition: processed time always exists } ``` -This function accepts only valid product codes, positive amounts, and valid ages. No need to read documentation—the types tell the whole story. +Constructor arguments express **preconditions** (conditions that must be satisfied for this object to exist), while `public readonly` properties express **postconditions** (states this object guarantees). Defensive programming becomes unnecessary. Argument validation, null checks, range verification, inventory confirmation, geographic constraints—semantic variables guarantee all of these. Code can focus on its true purpose: implementing business logic. diff --git a/manuals/1.0/en/07-type-driven-metamorphosis.md b/manuals/1.0/en/07-type-driven-metamorphosis.md index ce9ba5b..2d81bc7 100644 --- a/manuals/1.0/en/07-type-driven-metamorphosis.md +++ b/manuals/1.0/en/07-type-driven-metamorphosis.md @@ -7,144 +7,134 @@ permalink: /manuals/1.0/en/07-type-driven-metamorphosis.html # Type-Driven Metamorphosis -> "The object knows its own nature. We merely create the conditions for its becoming." +> "The Tao gives birth to one, one gives birth to two, two gives birth to three, three gives birth to all things" +> +>   —Laozi, *Tao Te Ching*, Chapter 42 (6th century BCE) -Type-Driven Metamorphosis represents the deepest transformation—where objects **discover their own destiny** through their nature. - -## Beyond Fixed Paths - -Traditional metamorphosis follows predetermined routes: +Type-driven metamorphosis enables objects to choose from multiple possible types based on conditions. Multiple classes are declared as arrays using the `#[Be()]` attribute, with the selection expressed through the being property: ```php -#[Be(UserProfile::class)] // Single destiny -final class UserInput +#[Be([Success::class, Failure::class])] +final class PaymentAttempt { - // Always becomes UserProfile, regardless of content -} -``` - -## Self-Determining Beings - -Type-Driven Metamorphosis allows objects to **choose their own becoming**: - -```php -#[Be([ActiveUser::class, InactiveUser::class])] -final class UserValidation -{ - public readonly ActiveUser|InactiveUser $being; // Being Property + public readonly Success|Failure $being; public function __construct( - #[Input] string $email, - #[Input] DateTime $lastLogin, - #[Inject] UserRepository $repository + #[Input] Money $amount, + #[Input] CreditCard $card, + #[Inject] PaymentGateway $gateway ) { - $daysSinceLogin = $lastLogin->diff(new DateTime())->days; + $result = $gateway->process($amount, $card); - // Self-determination of destiny - $this->being = $daysSinceLogin < 30 - ? new ActiveUser($email, $lastLogin) - : new InactiveUser($email, $lastLogin); + // Branching based on results + $this->being = $result->isSuccessful() + ? new Success($result) + : new Failure($result->getError()); } } ``` ## The Being Property -The **Being Property** is where self-determination manifests: +The `$being` property indicates the next transformation destination: + +```php +public readonly Success|Failure|Pending $being; +``` -- Must be a **union type** of all possible destinations -- Must be named exactly `being` -- Contains the object's chosen destiny +Classes are chosen when this type signature matches the constructor of the next class. +For example, if `$being` is of type `Success`, a class with the following constructor would be selected: ```php -public readonly SuccessfulPayment|FailedPayment $being; +class NextStep { + public function __construct(#[Input] Success $being) { ``` -## Natural Branching +`#[Be]` completely expresses all possibilities of an object. Types become the specification for workflows and use cases. -Objects choose their path based on **inner nature**: +## Multiple Type Selection Example ```php -#[Be([ChildAccount::class, AdultAccount::class, SeniorAccount::class])] -final class AgeBasedAccount +#[Be([VIPUser::class, RegularUser::class, SuspendedUser::class])] +final class UserClassification { - public readonly ChildAccount|AdultAccount|SeniorAccount $being; + public readonly VIPUser|RegularUser|SuspendedUser $being; public function __construct( - #[Input] int $age, - #[Input] string $name, - #[Inject] AccountFactory $factory + #[Input] UserActivity $activity, + #[Input] array $violations, + #[Inject] UserPolicy $policy ) { $this->being = match (true) { - $age < 18 => $factory->createChild($name, $age), - $age < 65 => $factory->createAdult($name, $age), - default => $factory->createSenior($name, $age) + $policy->shouldSuspend($violations) => new SuspendedUser($violations), + $activity->qualifiesForVIP() => new VIPUser($activity), + default => new RegularUser($activity) }; } } ``` -## Error States as Valid Beings +## Continuation Processing Mechanism -Failure is not an exception—it's a **valid form of existence**: +The advantage of type-driven processing lies in automatic continuation processing: ```php -#[Be([SuccessfulRegistration::class, FailedRegistration::class])] -final class UserRegistration -{ - public readonly SuccessfulRegistration|FailedRegistration $being; - - public function __construct( - #[Input] string $email, - #[Input] string $password, - #[Inject] UserService $userService - ) { - try { - $user = $userService->register($email, $password); - $this->being = new SuccessfulRegistration($user); - } catch (RegistrationException $e) { - $this->being = new FailedRegistration($e->getErrors()); - } - } -} +$evaluation = $becoming(new UserInput($data)); +$notification = $becoming($evaluation); // $evaluation->being is automatically selected ``` -Both success and failure are **equally valid beings**. +The framework detects the `$being` property and performs the next processing based on its type. External conditional branching becomes unnecessary. + +## Extended Decision-Making Prospects -## Metamorphosis Continuation +⚠️ **Note**: AMD (Advanced Decision-Making) is currently an unimplemented future concept. -The framework automatically extracts the Being Property for continued transformation: +Beyond deterministic judgment, a new paradigm that embraces uncertainty is being prepared: ```php -$classification = $becoming(new OrderInput($data)); -$processedOrder = $becoming($classification); // Uses being property automatically +// Future concept +#[Accept] // Unimplemented: delegation to experts +#[Be([Approved::class, Rejected::class, Undetermined::class])] +final class ComplexDecision +{ + public readonly Approved|Rejected|Undetermined $being; + + // Extended decision-making through AI-human collaboration +} ``` -## Philosophical Implications +A decision system where determinable things are decided by types, and indeterminate things are delegated to experts. -### Objects as Conscious Entities +## Elimination of Control Structures -Type-Driven Metamorphosis treats objects as **conscious beings** that understand their own nature. +Be Framework eliminates traditional "complex control structures within methods". The framework follows flows declared with `#[Be]` and selects the next class through type matching. -### Wu Wei in Code +Traditional complex conditional branching: -The programmer doesn't **force** transformation—they create conditions where objects naturally become what they are meant to be. - -### Elimination of Control Flow - -No `if-else` chains in business logic. The object's nature **is** the logic. +```php +if ($score > 800) { + return new Approved($amount); +} elseif ($score < 400) { + return new Rejected("Low score"); +} else { + return new Review($amount); +} +``` -## The Revolution +In type-driven metamorphosis, these are expressed as union types: -Being Property signatures become **documentation**: ```php -public readonly Success|Warning|Error $being; // All possibilities visible +public readonly Approved|Rejected|Review $being; ``` -Objects **self-determine** their destiny based on their essential nature, not external control. +## Integration with Type System + +Type-driven metamorphosis integrates complex decision logic into the type system. Union types make possible results explicit, while constructors handle the actual branching. This makes decision logic understandable and maintainable code. + +From the simple principle "if types match, proceed to the next", a rich workflow system that handles real-world complexity is constructed. --- -**Next**: Learn about [Reason Layer: Ontological Capabilities](07-reason-layer.md) where contextual capabilities shape transformation. +**Next**: Learn about the philosophy of dependency injection that supports metamorphosis in [Reason Layer: Ontological Capabilities](08-reason-layer.html). -*"We don't decide what objects become—we discover what they already are, in their deepest nature."* +*"Type-driven metamorphosis is a technique that integrates complex control flow into the type system itself."* diff --git a/manuals/1.0/en/08-reason-layer.md b/manuals/1.0/en/08-reason-layer.md index c028b14..81b71cc 100644 --- a/manuals/1.0/en/08-reason-layer.md +++ b/manuals/1.0/en/08-reason-layer.md @@ -5,185 +5,178 @@ category: Manual permalink: /manuals/1.0/en/08-reason-layer.html --- -# Reason Layer: Ontological Capabilities +# Reason Layer -> "Context is not decoration—it is the very condition of existence." +> "Everything that exists has a reason for its existence" +> +>   —Leibniz, *Principle of Sufficient Reason* (1714) -The Reason Layer embodies **Transcendent** forces—the contextual capabilities that shape how beings transform. +## Why This Name? -## Beyond Simple Services +The Reason Layer has two meanings of "reason": -Traditional dependency injection provides tools: +### 1. Reason for Type Matching + +First, the reason as criteria for determining the next transformation destination: ```php -public function __construct( - EmailService $emailService, // Just a tool - DatabaseService $database // Just a tool -) {} +final class BeGreeting +{ + public readonly CasualStyle|FormalStyle $being; + + public function __construct( + #[Input] string $name, + #[Input] string $style + ) { + // The condition 'formal' is the reason for choosing FormalStyle + $this->being = $style === 'formal' + ? new FormalStyle() + : new CasualStyle(); + } +} ``` -## Ontological Capabilities +### 2. Reason for Existence -The Reason Layer provides **contextual being-capabilities**: +Next, the reason as the foundation for why an object can be in that existence: ```php -public function __construct( - #[Input] string $message, // Immanent - #[Inject] #[English] CulturalGreeting $greeting, // Transcendent capability - #[Inject] #[Formal] BusinessProtocol $protocol // Transcendent context -) { - // Capability and context shape the transformation +final class FormalGreeting +{ + public readonly string $greeting; + public readonly string $businessCard; + + public function __construct( + #[Input] string $name, // Immanent property + #[Input] FormalStyle $being // Reason for existence + ) { + // FormalStyle provides the reason why this object can be FormalGreeting + $this->greeting = $being->formalGreeting($name); + $this->businessCard = $being->formalBusinessCard($name); + } } ``` -## Reason Classes: Ways of Being +`FormalGreeting` can exist as `FormalGreeting` because `FormalStyle` provides the necessary behaviors. This is the reason for existence. + +## Defining Reason Classes -Reason classes are **not services**—they are contextual ways of being: +Reason classes provide methods that realize specific modes of existence: ```php namespace App\Reason; -final class CasualStyle +final class FormalStyle { - public function format(string $message): string + public function formalGreeting(string $name): string { - return strtolower($message) . " 😊"; + return "Good morning, Mr./Ms. {$name}."; } - public function getGreeting(): string + public function formalBusinessCard(string $name): string { - return "Hey there!"; + return "【{$name}】\nI would like to extend my formal greetings."; } } -final class FormalStyle +final class CasualStyle { - public function format(string $message): string + public function casualGreeting(string $name): string { - return ucfirst($message) . "."; + return "Hey, {$name}!"; } - public function getGreeting(): string + public function casualMessage(string $name): string { - return "Good day."; + return "Hi {$name}! 😊 Nice to meet you!"; } } ``` -These are **ontological modes**—different ways of existing in specific contexts. +## Reason for Existence as Raison d'être -## Context-Driven Transformation - -The same object transforms differently based on contextual capabilities: +The Reason Layer provides the **raison d'être** of objects. ```php -final class FormattedGreeting +final class ValidatedUser { - public readonly string $greeting; - public readonly string $signature; - public function __construct( - #[Input] string $name, - #[Input] string $message, - #[Inject] StyleReason $style // Context shapes transformation + #[Input] string $email, + #[Input] ValidationReason $raisonDEtre // The raison d'être of this existence ) { - $this->greeting = $style->getGreeting() . " " . $name; - $this->signature = $style->format($message); + // ValidationReason provides the raison d'être for ValidatedUser } } ``` -## Cultural Context Ontologies +**raison d'être** means: +- Why an object can exist in that state +- The raison d'être of `ValidatedUser` is validation capability +- The raison d'être of `SavedUser` is saving capability +- The raison d'être of `DeletedUser` is deletion/archival capability -Applications naturally adapt to cultural contexts: +Reason objects provide the tool set necessary for an object to exist in that state. This is the origin of the name "Reason Layer" in the Be Framework. -```php -final class JapaneseEtiquette -{ - public function addHonorific(string $name): string - { - return $name . "-san"; - } - - public function formatGreeting(string $message): string - { - return "いつもお世話になっております。" . $message; - } -} +## Difference from #[Inject] -final class AmericanEtiquette -{ - public function addHonorific(string $name): string - { - return $name; // No honorific needed - } +The unique value of the Reason Layer becomes clear when compared to traditional dependency injection: + +**Traditional Inject**: +```php +public function __construct( + #[Input] string $email, + #[Inject] EmailValidator $emailValidator, + #[Inject] PasswordChecker $passwordChecker, + #[Inject] SecurityAuditor $auditor, + #[Inject] DatabaseSaver $saver +) { + // Using scattered tools individually } ``` -## Strategy as Ontology - -Unlike the Strategy pattern, Reason classes represent **ways of being**, not algorithms: - +**Reason Layer**: ```php -interface PricingOntology -{ - public function interpretValue(Money $price): PriceCategory; +public function __construct( + #[Input] string $email, + #[Input] UserValidationReason $reason // Related tools bundled as reason for existence +) { + // A complete tool set for becoming ValidatedUser is provided + $this->result = $reason->validateUser($email, $this); } +``` -final class LuxuryMarketOntology implements PricingOntology -{ - // In luxury context, high price means exclusivity -} +**Differences**: +- **Inject**: Individual tools injected separately +- **Reason Layer**: Provided as a semantically coherent "tool set for achieving that state" -final class MassMarketOntology implements PricingOntology -{ - // In mass market, high price means barrier -} -``` +**Value**: +- **Conceptual coherence**: "What is needed to become ValidatedUser?" is clear +- **Simplified testing**: Mock one reason object instead of many +- **Separation of concerns**: Related tools are consolidated in one place + +## State Realization Through Delegation -## Multiple Contextual Capabilities +In the Reason Layer, objects delegate the realization of their state to reason objects: ```php -final class InternationalMessage +final class SavedUser { public function __construct( - #[Input] string $recipientName, - #[Input] string $message, - #[Inject] CulturalEtiquette $culture, // Cultural context - #[Inject] CommunicationProtocol $protocol, // Communication context - #[Inject] FormalityLevel $formality // Formality context + #[Input] UserData $data, + #[Input] SaveReason $reason // Receive reason for existence ) { - $name = $culture->addHonorific($recipientName); - $greeting = $culture->formatGreeting($message); - $styled = $formality->apply($greeting); - - $this->content = $protocol->format($styled); + // Delegate saving process to reason for existence + $this->result = $reason->saveUser($data); } } ``` -## Dependency Resolution - -Context-aware binding through dependency injection: - -```php -$injector->bind(PaymentGateway::class) - ->annotatedWith(Production::class) - ->to(StripeGateway::class); - -$injector->bind(PaymentGateway::class) - ->annotatedWith(Testing::class) - ->to(MockGateway::class); -``` - -## The Revolution - -The Reason Layer transforms dependency injection from **tool provision** to **ontological context**. +Objects themselves declare "what to become", while reason objects realize "how to achieve that state". This separation clearly divides state definition from realization means. -Objects don't just receive services—they receive **ways of being** appropriate to their environment. +`SavedUser` requires a saving tool set, `ValidatedUser` requires a validation tool set. Reason objects clearly organize "what is needed to achieve this state?" and follow the single responsibility principle, making tests concise as well. --- -**Next**: Learn about [Error Handling & Validation](08-error-handling.md) where semantic exceptions preserve meaning. +**Next**: Learn about meaning preservation in errors through [Validation and Error Handling](09-error-handling.html). -*"The Reason Layer is where the world's capabilities meet the object's nature—as contextual condition for meaningful becoming."* +*"The Reason Layer provides the tool set necessary for objects to realize their mode of existence."* \ No newline at end of file diff --git a/manuals/1.0/en/09-error-handling.md b/manuals/1.0/en/09-error-handling.md index a4da1ac..3695f00 100644 --- a/manuals/1.0/en/09-error-handling.md +++ b/manuals/1.0/en/09-error-handling.md @@ -5,68 +5,76 @@ category: Manual permalink: /manuals/1.0/en/09-error-handling.html --- -# Error Handling & Validation +# Error Handling -> "What cannot be must be understood. Failure preserves meaning through clear language." +> "I have not failed. I've just found 10,000 ways that won't work" +> +>   —Thomas Edison (1847-1931) -Error handling in Be Framework is not about catching exceptions—it's about **preserving meaning when existence fails**. +## Meaningful Failures -## Beyond Generic Exceptions - -Traditional error handling loses meaning: +In Be Framework, errors are not mere "failures" but **specific reasons why existence is impossible**. We use semantic exceptions instead of generic ones: ```php -try { - $user = new User($name, $email, $age); -} catch (Exception $e) { - // What went wrong? Why? How to fix it? +// Traditional generic error +catch (Exception $e) { echo $e->getMessage(); // "Validation failed" } -``` -## Semantic Exceptions: Meaning in Failure - -Every failure carries **specific ontological meaning**: - -```php -try { - $user = $becoming(new UserInput($name, $email, $age)); -} catch (SemanticVariableException $e) { +// Semantic exceptions +catch (SemanticVariableException $e) { foreach ($e->getErrors()->exceptions as $exception) { echo get_class($exception) . ": " . $exception->getMessage(); - // EmptyNameException: Name cannot be empty. - // InvalidEmailFormatException: Email format is invalid. - // AgeTooYoungException: Age must be at least 13. + // EmptyNameException: Name cannot be empty + // InvalidEmailException: Invalid email format } } ``` -## Exception Hierarchy +## Domain Exception Classes -Domain exceptions form meaningful categories: +In Be Framework, all exceptions inherit from `DomainException`: ```php abstract class DomainException extends Exception {} final class EmptyNameException extends DomainException {} -final class InvalidEmailFormatException extends DomainException +final class InvalidEmailException extends DomainException { public function __construct(public readonly string $invalidEmail) { - parent::__construct("Email format is invalid: {$invalidEmail}"); + parent::__construct("Invalid email format: {$invalidEmail}"); + } +} + +final class AgeTooYoungException extends DomainException +{ + public function __construct(public readonly int $age, public readonly int $min = 13) + { + parent::__construct("Age insufficient: {$age} years (minimum {$min} years)"); } } +``` + +Since all exceptions are domain exceptions, technical exceptions (`RuntimeException`, `InvalidArgumentException`, etc.) are not used. Failures are always expressed as **failures with domain meaning**. -// Age-related existence failures -abstract class AgeException extends DomainException {} -final class NegativeAgeException extends AgeException {} -final class AgeTooHighException extends AgeException {} +Domain exceptions hold not just messages but **structured data**. From the `$invalidEmail` property, programs can access the invalid email address value and utilize it for various purposes: human-readable display, API JSON responses, AI analysis, etc. + +```php +catch (InvalidEmailException $e) { + $logData = [ + 'invalid_email' => $e->invalidEmail, // Programmatically accessible + 'user_ip' => $request->getClientIp(), + 'timestamp' => now() + ]; + Logger::warning('Invalid email attempt', $logData); +} ``` ## Multilingual Error Messages -Semantic exceptions speak the user's language: +The `#[Message]` attribute enables multilingual error messages: ```php #[Message([ @@ -77,42 +85,38 @@ Semantic exceptions speak the user's language: final class EmptyNameException extends DomainException {} #[Message([ - 'en' => 'Age must be between {min} and {max} years.', - 'ja' => '年齢は{min}歳から{max}歳の間でなければなりません。' + 'en' => 'Age must be at least {min} years.', + 'ja' => '年齢は最低{min}歳でなければなりません。' ])] -final class AgeOutOfRangeException extends DomainException +final class AgeTooYoungException extends DomainException { - public function __construct( - public readonly int $age, - public readonly int $min = 0, - public readonly int $max = 150 - ) {} + public function __construct(public readonly int $min = 13) {} } ``` -## Automatic Error Collection +## Automatic Collection of All Errors -The framework collects **all validation failures** before throwing: +The framework collects **all validation errors** before throwing an exception: ```php -final class UserValidation -{ - public function __construct( - #[Input] string $name, // May throw EmptyNameException - #[Input] string $email, // May throw InvalidEmailFormatException - #[Input] int $age // May throw NegativeAgeException - ) { - // If ANY validation fails, ALL errors are collected - // Single SemanticVariableException contains everything - } +try { + $user = $becoming(new UserInput('', 'invalid-email', 10)); +} catch (SemanticVariableException $e) { + // Three errors are collected simultaneously: + // - EmptyNameException + // - InvalidEmailException + // - AgeTooYoungException + + $messages = $e->getErrors()->getMessages('en'); + // ["Name cannot be empty", "Invalid email format", "Age must be at least 13"] } ``` -No "fail fast"—**fail completely with full understanding**. +Rather than "stop at first error", you can **understand all problems at once**. -## Error Recovery Patterns +## Metamorphosis Including Errors -Errors become **valid beings** in their own right: +Error states can also be treated as valid metamorphosis results: ```php #[Be([ValidUser::class, InvalidUser::class])] @@ -120,13 +124,10 @@ final class UserValidation { public readonly ValidUser|InvalidUser $being; - public function __construct( - #[Input] string $name, - #[Input] string $email, - #[Input] int $age - ) { + public function __construct(#[Input] string $data) + { try { - $this->being = new ValidUser($name, $email, $age); + $this->being = new ValidUser($data); } catch (ValidationException $e) { $this->being = new InvalidUser($e->getErrors()); } @@ -134,64 +135,12 @@ final class UserValidation } ``` -## Semantic Logging Integration - -Validation failures are automatically logged with context: - -```php -{ - "event": "metamorphosis_failed", - "source_class": "UserInput", - "destination_class": "UserProfile", - "errors": [ - { - "exception": "EmptyNameException", - "message": "Name cannot be empty", - "field": "name", - "value": "" - } - ] -} -``` - -## Development vs Production - -```php -// Development: Verbose error details -if (app()->environment('local')) { - $errors->getDetailedMessages(); -} - -// Production: User-friendly messages -$errors->getMessages('en'); -// ["Name cannot be empty.", "Email format is invalid."] -``` - -## Testing Error Conditions - -```php -public function testCollectsAllValidationErrors(): void -{ - try { - $becoming(new UserInput('', 'invalid-email', -5)); - $this->fail('Expected SemanticVariableException'); - } catch (SemanticVariableException $e) { - $errors = $e->getErrors(); - $this->assertCount(3, $errors->exceptions); - } -} -``` - -## The Revolution - -Semantic exceptions transform error handling from **problem reporting** to **meaning preservation**. - -When existence fails, the reason becomes **clear, actionable, and multilingual**. +Errors can be expressed as types rather than stopping execution with exceptions. -Errors are not obstacles—they are **valid beings** that guide users toward successful transformation. +Semantic exceptions make failure reasons clear, enabling users to understand specific correction methods. Error handling changes from problem reporting to **guidance toward problem resolution**. --- -**Next**: Learn about [The Philosophy Behind](09-philosophy-behind.md) to understand the deeper principles. +**Next**: Learn about the evolution of programming paradigms in [From Doing to Being](10-from-doing-to-being-final.html). -*"Semantic exceptions don't just report failure—they preserve the meaning of what cannot exist."* +*"Semantic exceptions specifically teach us why existence is impossible."* diff --git a/manuals/1.0/en/10-semantic-logging.md b/manuals/1.0/en/10-semantic-logging.md new file mode 100644 index 0000000..73d4b61 --- /dev/null +++ b/manuals/1.0/en/10-semantic-logging.md @@ -0,0 +1,62 @@ +--- +layout: docs-en +title: "10. Semantic Logging" +category: Manual +permalink: /manuals/1.0/en/10-semantic-logging.html +--- + +# Semantic Logging + +> "What we record becomes memory; what we remember becomes truth" +> +> —Adaptation of Orwell's concept from '1984' (1949) + +## Overview + +Be Framework implements **semantic logging** functionality that automatically records object metamorphosis processes as structured logs. + +### Basic Concept + +**Traditional Logs**: Fragmented event records +**Semantic Logs**: Complete metamorphosis story records of objects + +```php +// Object metamorphosis... +#[Be(RegisteredUser::class)] +final class UserInput { /* ... */ } + +final class RegisteredUser { /* ... */ } + +// Automatically recorded as structured logs +{ + "metamorphosis": { + "from": "UserInput", + "to": "RegisteredUser", + // Complete metamorphosis information... + } +} +``` + +## Technical Foundation + +Integrated with [Koriym.SemanticLogger](https://github.com/koriym/Koriym.SemanticLogger): + +- **Type-safe structured logging** +- **Open/Event/Close pattern** +- **JSON schema validation** +- **Hierarchical operation tracking** + +## Value Provided + +### Development & Debugging +Complete tracking of object metamorphosis makes it easy to understand complex processing flows and identify problems. + +### Audit & Compliance +Since all metamorphoses are recorded as structured data, complete audit trails can be provided. + +### System Analysis +Analysis of object growth patterns and processing efficiency becomes possible. + +--- + +**Detailed usage methods, configuration examples, and practical samples will be documented at a later date.** \ No newline at end of file diff --git a/manuals/1.0/en/11-reference-resources.md b/manuals/1.0/en/11-reference-resources.md new file mode 100644 index 0000000..b8d07a9 --- /dev/null +++ b/manuals/1.0/en/11-reference-resources.md @@ -0,0 +1,39 @@ +--- +layout: docs-en +title: "11. PR" +category: Manual +permalink: /manuals/1.0/en/11-reference-resources.html +--- + +# Reference + +> "Knowledge is only completed through practice" +> +> —Lao Tzu, Tao Te Ching, Chapter 41 + +Essential resources and links for Be Framework project development. + +## Official Repositories + +- **Be Framework Core**: [https://github.com/koriym/be-framework](https://github.com/koriym/be-framework) + Framework core and libraries + +- **Application Skeleton**: [https://github.com/be-framework/app](https://github.com/be-framework/app) + Project starter application skeleton + +- **Concept Stage Documentation**: [https://github.com/koriym/be-framework/blob/manual/concept/docs/README.md](https://github.com/koriym/be-framework/blob/manual/concept/docs/README.md) + Early documentation exploring framework design philosophy evolution + +## Development Reference + +### Naming Conventions +Naming standards for project development: +- [**Be Framework Naming Standards**](convention/naming-standards.html) - Being-oriented naming principles + +### Theoretical Background +Be Framework's philosophical foundations: +- [**The Philosophy Behind**](12-philosophy-behind.html) - Wu Wei, ontological programming, and philosophical roots + +--- + +*"Be, Don't Do"* diff --git a/manuals/1.0/en/11-semantic-logging.md b/manuals/1.0/en/11-semantic-logging.md deleted file mode 100644 index fa36e4a..0000000 --- a/manuals/1.0/en/11-semantic-logging.md +++ /dev/null @@ -1,93 +0,0 @@ ---- -layout: docs-en -title: "11. Semantic Logging" -category: Manual -permalink: /manuals/1.0/en/11-semantic-logging.html ---- - -# Semantic Logging - -> "Every transformation tells a story. Semantic logging captures that narrative." - -Semantic logging in Be Framework automatically captures the complete metamorphosis journey, providing deep observability into object transformations. - -## What is Semantic Logging? - -Traditional logging captures events. **Semantic logging captures meaning** - the ontological journey of objects through their transformations. - -Be Framework automatically logs every metamorphosis without any code changes required. - -## Automatic Log Structure - -### Open Context (Transformation Begins) -```json -{ - "open": { - "context": { - "fromClass": "UserInput", - "beAttribute": "#[Be(RegisteredUser::class)]", - "immanentSources": { - "email": "user@example.com" - }, - "transcendentSources": { - "UserRepository": "App\\Repository\\UserRepository" - } - } - } -} -``` - -### Close Context (Transformation Completes) -```json -{ - "close": { - "context": { - "be": "FinalDestination", - "properties": { - "userId": "user_123", - "email": "user@example.com" - } - } - } -} -``` - -## Configuration and Usage - -### Enabling Semantic Logging -Be Framework automatically uses [Koriym.SemanticLogger](https://github.com/koriym/Koriym.SemanticLogger) for structured semantic logging. - -**TBD** - Configuration details for enabling/disabling log output - -### Schema-Validated Logs -Semantic logs follow JSON schema for type safety and AI analysis: - -- **Type-safe structured logging** with validation -- **AI-native analysis** capabilities -- **Hierarchical workflow context** (intent → events → result) - -### Custom Log Context -**TBD** - How to add custom context to metamorphosis logs - -### Log Processing -**TBD** - Integration with monitoring tools and log aggregation - -## Log Analysis Examples - -```bash -# Find failed transformations -jq '.close.context.be == "DestinationNotFound"' logs/semantic.log - -# Follow specific user journeys -jq '.open.context.immanentSources.email == "user@example.com"' logs/semantic.log -``` - -## The Power of Ontological Observability - -Semantic logging transforms debugging from **"what happened?"** to **"what became?"** - -Instead of tracking method calls, you track the natural evolution of objects through their intended forms - providing unprecedented insight into your application's true behavior. - ---- - -*"In traditional logging, we track events. In semantic logging, we witness becoming."* diff --git a/manuals/1.0/en/12-from-doing-to-being-final.md b/manuals/1.0/en/12-from-doing-to-being-final.md deleted file mode 100644 index 5c63655..0000000 --- a/manuals/1.0/en/12-from-doing-to-being-final.md +++ /dev/null @@ -1,122 +0,0 @@ ---- -layout: docs-en -title: "12. From Doing to Being: The Bigger Picture" -category: Manual -permalink: /manuals/1.0/en/12-from-doing-to-being-final.html ---- - -# From Doing to Being: The Bigger Picture - -> "All things that exist are in the process of becoming." -> -> —Heraclitus, Fragments (c. 500 BC) - -## What You Have Discovered - -You've written Input Classes, created Being Classes, and watched objects transform rather than mutate. - -Now, let's understand what you've actually discovered. - -## The Timeline That Changes Everything - -Look at the history of programming paradigms: - -### Imperative (1950s) -```text -DO this, THEN DO that -``` -World understanding: Reality is sequences of actions - -### Object-Oriented (1980s) -```java -object.doSomething(); -user.doValidate(); -``` -World understanding: Reality is entities performing actions -*Why it won: Closer to how we see the world—things doing things* - -### Functional (2000s) -```haskell -doTransform :: Input -> Output -``` -World understanding: Reality is mathematical transformations -*Why it grew: Purity and predictability matter* - -### What's Next? -```php -new DeletedUser($activeUser); -``` -What if... reality is entities becoming? -*What if... everything that exists, exists in time?* - -Do you see it now? - -For 70 years, every paradigm started with the same assumption: **DO**. - -The invisible thread. The unquestioned premise. - -Until you started questioning it. - -## Remember Your First DeletedUser? - -When you first wrote: -```php -$deletedUser = new DeletedUser($activeUser); -``` - -That discomfort you felt? It was your mind recognizing that deletion doesn't destroy—it transforms. A deleted user isn't nothing. It's a user in a different state of being. - -## The Deeper Truth - -Each programming paradigm embodies a different understanding of reality: - -- **Procedural**: The world as mechanical sequences -- **Object-Oriented**: The world as interacting entities -- **Functional**: The world as mathematical truth -- **What you've been practicing**: The world as temporal becoming - -The revolution isn't in the syntax. It's in how we understand what programs **are**. - -## Why OOP Lasted 50 Years - -Object-Oriented Programming dominated not because of encapsulation or inheritance, but because it gave us a better way to understand reality—as autonomous entities interacting. - -But OOP missed something crucial: **time**. - -In OOP, objects exist in an eternal present: -```java -person.setAge(25); -person.setAge(30); -person.setAge(25); // Time runs backward? -``` - -In the approach you've learned, time flows in one direction: -```php -$child = new Child($birthData); -$teenager = new Teenager($child); -$adult = new Adult($teenager); -// No going back -``` - -## What You've Discovered - -Through practice, you've learned: - -1. **Objects don't DO things—they BECOME** -2. **Transformation is irreversible** -3. **Existence implies correctness** -4. **Time gives meaning to change** - -You haven't just learned a new framework. You've acquired new eyes. - -## The Journey Continues - -After 70 years of asking "How should we DO?", you've started asking "What should BE?" - -This isn't the end—it's the beginning of a new way of thinking about software. - -Welcome to programming where code doesn't just execute—it exists, transforms, and becomes. - ---- - -> *"We thought we were learning a framework. We were actually discovering a new way to see."* diff --git a/manuals/1.0/en/10-philosophy-behind.md b/manuals/1.0/en/12-philosophy-behind.md similarity index 97% rename from manuals/1.0/en/10-philosophy-behind.md rename to manuals/1.0/en/12-philosophy-behind.md index d37259e..d8dc5f1 100644 --- a/manuals/1.0/en/10-philosophy-behind.md +++ b/manuals/1.0/en/12-philosophy-behind.md @@ -1,8 +1,8 @@ --- layout: docs-en -title: "10. The Philosophy Behind" -category: Manual -permalink: /manuals/1.0/en/10-philosophy-behind.html +title: "12. The Philosophy Behind" +category: Philosophy +permalink: /manuals/1.0/en/12-philosophy-behind.html --- # The Philosophy Behind diff --git a/manuals/1.0/en/index.md b/manuals/1.0/en/index.md index cdbfb37..d6ec02e 100644 --- a/manuals/1.0/en/index.md +++ b/manuals/1.0/en/index.md @@ -21,8 +21,8 @@ Intermediate transformations through Immanent + Transcendent interactions ## [4. Final Objects](04-final-objects.html) The destination of metamorphosis - complete transformed beings -## [5. Metamorphosis Patterns](05-metamorphosis.html) -Simple chains, branching destinies, and complex transformations +## [5. Metamorphosis](05-metamorphosis.html) +Inseparability of time and domain, self-determination of destiny ## [6. Semantic Variables](06-semantic-variables.html) Domain-specific validation and ontological type safety @@ -36,15 +36,12 @@ Understanding transcendent capabilities and contextual ontologies ## [9. Error Handling & Validation](09-error-handling.html) Semantic exceptions and multilingual error messages -## [10. The Philosophy Behind](10-philosophy-behind.html) -Wu Wei, Immanent/Transcendent principles, and BE = Be, Everything +## [10. Semantic Logging](10-semantic-logging.html) +Structured recording and audit trails of object metamorphosis -## [11. Semantic Logging](11-semantic-logging.html) -Automatic metamorphosis tracking and ontological observability - -## [12. From Doing to Being: The Bigger Picture](12-from-doing-to-being-final.html) -Understanding the paradigm shift and its place in programming history +## [11. Reference](11-reference-resources.html) +Essential resources and links for framework development --- -*"In Be Framework, we don't make objects do things. We create the conditions for them to become what they already are, in their deepest nature."* \ No newline at end of file +*"Be, Don't Do"* \ No newline at end of file diff --git a/manuals/1.0/ja/07-type-driven-metamorphosis.md b/manuals/1.0/ja/07-type-driven-metamorphosis.md index d61dd80..106c5b4 100644 --- a/manuals/1.0/ja/07-type-driven-metamorphosis.md +++ b/manuals/1.0/ja/07-type-driven-metamorphosis.md @@ -7,144 +7,136 @@ permalink: /manuals/1.0/ja/07-type-driven-metamorphosis.html # 型駆動変容 -> 「オブジェクトは自身の性質を知っています。私たちは単に、その成長のための条件を作り出すだけです。」 +> 「道生一、一生二、二生三、三生万物」 +> +>   —老子『道徳経』第四十二章(紀元前6世紀) -型駆動変容は最も深い変容を表します—オブジェクトがその性質を通して**自身の運命を発見する**場所です。 +## 型駆動による変容 -## 固定されたパスを超えて - -従来の変容は予め決められたルートに従います: - -```php -#[Be(UserProfile::class)] // 単一の運命 -final class UserInput -{ - // 内容に関係なく、常にUserProfileになる -} -``` - -## 自己決定する存在 - -型駆動変容はオブジェクトが**自身の成長を選択する**ことを許可します: +型駆動変容では、オブジェクトが複数の可能な型から条件に応じて選択します。`#[Be()]`属性で複数のクラスを配列として宣言し、beingプロパティでその選択を表現します: ```php -#[Be([ActiveUser::class, InactiveUser::class])] -final class UserValidation +#[Be([Success::class, Failure::class])] +final class PaymentAttempt { - public readonly ActiveUser|InactiveUser $being; // 存在プロパティ + public readonly Success|Failure $being; public function __construct( - #[Input] string $email, - #[Input] DateTime $lastLogin, - #[Inject] UserRepository $repository + #[Input] Money $amount, + #[Input] CreditCard $card, + #[Inject] PaymentGateway $gateway ) { - $daysSinceLogin = $lastLogin->diff(new DateTime())->days; + $result = $gateway->process($amount, $card); - // 運命の自己決定 - $this->being = $daysSinceLogin < 30 - ? new ActiveUser($email, $lastLogin) - : new InactiveUser($email, $lastLogin); + // 結果に応じた分岐 + $this->being = $result->isSuccessful() + ? new Success($result) + : new Failure($result->getError()); } } ``` -## 存在プロパティ +## beingプロパティ + +`$being`プロパティは次の変容先を示すプロパティです: -**存在プロパティ**は自己決定が現れる場所です: +```php +public readonly Success|Failure|Pending $being; +``` -- すべての可能な目的地の**ユニオン型**でなければなりません -- 正確に`being`と名付けられなければなりません -- オブジェクトの選択された運命を含みます +次のクラスのコンストラクタでこの型シグネチャがマッチするクラスが選ばれます。 +例えば`$being`が`Success`型なら、以下のコンストラクタを持つクラスが選択されます: ```php -public readonly SuccessfulPayment|FailedPayment $being; +class NextStep { + public function __construct(#[Input] Success $being) { ``` -## 自然な分岐 +`#[Be]`がオブジェクトの全ての可能性を完全に表現します。型がワークフローやユースケースの仕様になります。 -オブジェクトは**内なる性質**に基づいて自身の道を選択します: +## 複数型の選択例 ```php -#[Be([ChildAccount::class, AdultAccount::class, SeniorAccount::class])] -final class AgeBasedAccount +#[Be([VIPUser::class, RegularUser::class, SuspendedUser::class])] +final class UserClassification { - public readonly ChildAccount|AdultAccount|SeniorAccount $being; + public readonly VIPUser|RegularUser|SuspendedUser $being; public function __construct( - #[Input] int $age, - #[Input] string $name, - #[Inject] AccountFactory $factory + #[Input] UserActivity $activity, + #[Input] array $violations, + #[Inject] UserPolicy $policy ) { $this->being = match (true) { - $age < 18 => $factory->createChild($name, $age), - $age < 65 => $factory->createAdult($name, $age), - default => $factory->createSenior($name, $age) + $policy->shouldSuspend($violations) => new SuspendedUser($violations), + $activity->qualifiesForVIP() => new VIPUser($activity), + default => new RegularUser($activity) }; } } ``` -## 有効な存在としてのエラー状態 +## 継続処理の仕組み -失敗は例外ではありません—それは**有効な存在形態**です: +型駆動処理の利点は、自動的な継続処理にあります: ```php -#[Be([SuccessfulRegistration::class, FailedRegistration::class])] -final class UserRegistration -{ - public readonly SuccessfulRegistration|FailedRegistration $being; - - public function __construct( - #[Input] string $email, - #[Input] string $password, - #[Inject] UserService $userService - ) { - try { - $user = $userService->register($email, $password); - $this->being = new SuccessfulRegistration($user); - } catch (RegistrationException $e) { - $this->being = new FailedRegistration($e->getErrors()); - } - } -} +$evaluation = $becoming(new UserInput($data)); +$notification = $becoming($evaluation); // $evaluation->beingが自動選択される ``` -成功と失敗の両方が**等しく有効な存在**です。 +フレームワークは`$being`プロパティを検出し、その型に応じて次の処理を行います。外部の条件分岐は不要になります。 + +## 拡張意思決定の展望 -## 変容の継続 +⚠️ **注記**: AMD(拡張意思決定)は現在未実装の将来構想です。 -フレームワークは継続的な変容のために存在プロパティを自動的に抽出します: +確定的判断を超えて、不確実性を受容する新しいパラダイムが準備されています: ```php -$classification = $becoming(new OrderInput($data)); -$processedOrder = $becoming($classification); // 自動的に存在プロパティを使用 +// 将来構想 +#[Accept] // 未実装:専門家への委譲 +#[Be([Approved::class, Rejected::class, Undetermined::class])] +final class ComplexDecision +{ + public readonly Approved|Rejected|Undetermined $being; + + // AIと人間の協調による拡張意思決定 +} ``` -## 哲学的含意 +確定できるものは型で決定し、不確定なものは専門家に委譲する意思決定システムです。 -### 意識的エンティティとしてのオブジェクト +## 制御構造の排除 -型駆動変容はオブジェクトを自身の性質を理解する**意識的存在**として扱います。 +Be Frameworkは従来の"メソッドの中にある複雑な制御構造"を排除します。フレームワークは`#[Be]`で宣言された流れに従い、型マッチングで次のクラスを選択します。 -### コードにおける無為 +従来の複雑な条件分岐: -プログラマは変容を**強制**しません—オブジェクトが自然にあるべき姿になる条件を作り出します。 - -### 制御フローの排除 - -ビジネスロジックに`if-else`チェーンはありません。オブジェクトの性質**が**ロジックです。 +```php +if ($score > 800) { + return new Approved($amount); +} elseif ($score < 400) { + return new Rejected("Low score"); +} else { + return new Review($amount); +} +``` -## 革命 +型駆動変容では、これらがユニオン型で表現されます: -存在プロパティシグネチャは**ドキュメント**になります: ```php -public readonly Success|Warning|Error $being; // すべての可能性が見える +public readonly Approved|Rejected|Review $being; ``` -オブジェクトは外部制御ではなく、本質的な性質に基づいて運命を**自己決定**します。 +## 型システムとの統合 + +型駆動変容により、複雑な決定ロジックが型システムに統合されます。ユニオン型が可能な結果を明示し、コンストラクタが実際の分岐を処理します。これにより、決定ロジックが理解しやすく、保守しやすいコードになります。 + +「型がマッチすれば次に進む」という単純な原理から、現実の複雑さに対応する豊かなワークフローシステムが構築されます。 --- -**次へ**: 文脈的能力が変容を形作る[理性層: 存在論的能力](08-reason-layer.html)について学びましょう。 +**次へ**: 変容を支える依存性注入の哲学について[理性層: 存在論的能力](08-reason-layer.html)で学びましょう。 -> 「私たちはオブジェクトが何になるかを決定するのではありません—オブジェクトが最も深い性質においてすでに何であるかを発見するのです。」 +> 「型駆動変容は、複雑な制御フローを型システムに統合する手法です。」 diff --git a/manuals/1.0/ja/08-reason-layer.md b/manuals/1.0/ja/08-reason-layer.md index 7c9668b..f0f0a41 100644 --- a/manuals/1.0/ja/08-reason-layer.md +++ b/manuals/1.0/ja/08-reason-layer.md @@ -5,185 +5,178 @@ category: Manual permalink: /manuals/1.0/ja/08-reason-layer.html --- -# 存在理由層: 存在論的能力 +# 存在理由層 -> 「文脈は装飾ではありません—それは存在の条件そのものです。」 +> 「すべてのものには、それが存在するための理由がある」 +> +>   —ライプニッツ『充足理由律』(1714年) -存在理由層は**超越的**な力—存在の変容を形成する文脈的能力を体現します。 +## なぜこの名前か? -## 単純なサービスを超えて +存在理由層には2つの「理由」があります。 -従来の依存性注入はツールを提供します: +### 1. 型マッチングの理由 + +まず、次の変容先を決定する判断基準としての理由: ```php -public function __construct( - EmailService $emailService, // ただのツール - DatabaseService $database // ただのツール -) {} +final class BeGreeting +{ + public readonly CasualStyle|FormalStyle $being; + + public function __construct( + #[Input] string $name, + #[Input] string $style + ) { + // 'formal'という条件が FormalStyle を選ぶ理由 + $this->being = $style === 'formal' + ? new FormalStyle() + : new CasualStyle(); + } +} ``` -## 存在論的能力 +### 2. 存在の理由 -存在理由層は**文脈的存在能力**を提供します: +次に、オブジェクトがその存在でいるための根拠としての理由: ```php -public function __construct( - #[Input] string $message, // 内在的 - #[Inject] #[English] CulturalGreeting $greeting, // 超越的能力 - #[Inject] #[Formal] BusinessProtocol $protocol // 超越的文脈 -) { - // 能力と文脈が変容を形成する +final class FormalGreeting +{ + public readonly string $greeting; + public readonly string $businessCard; + + public function __construct( + #[Input] string $name, // 内在的性質 + #[Input] FormalStyle $being // 存在理由 + ) { + // FormalStyleが、このオブジェクトがFormalGreetingでいる理由を提供 + $this->greeting = $being->formalGreeting($name); + $this->businessCard = $being->formalBusinessCard($name); + } } ``` -## 存在理由クラス: 存在の方法 +`FormalGreeting`が`FormalGreeting`として存在できるのは、`FormalStyle`が必要な振る舞いを提供するからです。これが存在の理由です。 + +## 存在理由クラスの定義 -存在理由クラスは**サービスではありません**—文脈的な存在の方法です: +存在理由クラスは、特定の存在様式を実現するメソッドを提供します: ```php namespace App\Reason; -final class CasualStyle +final class FormalStyle { - public function format(string $message): string + public function formalGreeting(string $name): string { - return strtolower($message) . " 😊"; + return "おはようございます、{$name}様。"; } - public function getGreeting(): string + public function formalBusinessCard(string $name): string { - return "やあ!"; + return "【{$name}様】\n正式なご挨拶をさせていただきます。"; } } -final class FormalStyle +final class CasualStyle { - public function format(string $message): string + public function casualGreeting(string $name): string { - return ucfirst($message) . "。"; + return "やあ、{$name}!"; } - public function getGreeting(): string + public function casualMessage(string $name): string { - return "おはようございます。"; + return "Hi {$name}! 😊 よろしく!"; } } ``` -これらは**存在論的モード**—特定の文脈で存在する異なる方法です。 +## raison d'être としての存在理由 -## 文脈駆動変容 - -同じオブジェクトが文脈的能力に基づいて異なって変容します: +存在理由層は、オブジェクトの**raison d'être**(レーゾンデートル:存在理由)を提供します。 ```php -final class FormattedGreeting +final class ValidatedUser { - public readonly string $greeting; - public readonly string $signature; - public function __construct( - #[Input] string $name, - #[Input] string $message, - #[Inject] StyleReason $style // 文脈が変容を形成する + #[Input] string $email, + #[Input] ValidationReason $raisonDEtre // この存在の raison d'être ) { - $this->greeting = $style->getGreeting() . " " . $name; - $this->signature = $style->format($message); + // ValidationReasonが、ValidatedUserの存在理由を提供 } } ``` -## 文化的文脈存在論 +**raison d'être**とは: +- なぜそのオブジェクトがその存在でいられるのか +- `ValidatedUser`の raison d'être は検証能力 +- `SavedUser`の raison d'être は保存能力 +- `DeletedUser`の raison d'être は削除・アーカイブ能力 -アプリケーションは自然に文化的文脈に適応します: +存在理由オブジェクトは、そのオブジェクトがその状態でいるために必要な道具セットを提供します。これがBeフレームワークの「存在理由層」の名前の由来です。 -```php -final class JapaneseEtiquette -{ - public function addHonorific(string $name): string - { - return $name . "さん"; - } - - public function formatGreeting(string $message): string - { - return "いつもお世話になっております。" . $message; - } -} +## #[Inject]との違い -final class AmericanEtiquette -{ - public function addHonorific(string $name): string - { - return $name; // 敬語は不要 - } +存在理由層の独自価値は、従来の依存性注入との比較で明確になります: + +**従来のInject**: +```php +public function __construct( + #[Input] string $email, + #[Inject] EmailValidator $emailValidator, + #[Inject] PasswordChecker $passwordChecker, + #[Inject] SecurityAuditor $auditor, + #[Inject] DatabaseSaver $saver +) { + // バラバラの道具を個別に使用 } ``` -## 存在論としての戦略 - -戦略パターンとは異なり、存在理由クラスはアルゴリズムではなく**存在の方法**を表します: - +**存在理由層**: ```php -interface PricingOntology -{ - public function interpretValue(Money $price): PriceCategory; +public function __construct( + #[Input] string $email, + #[Input] UserValidationReason $reason // 関連道具がまとまった存在理由 +) { + // ValidatedUserになるための道具一式が提供される + $this->result = $reason->validateUser($email, $this); } +``` -final class LuxuryMarketOntology implements PricingOntology -{ - // 高級文脈では、高価格は独占性を意味する -} +**違い**: +- **Inject**: 個別の道具を別々に注入 +- **存在理由層**: 「その状態になるための道具セット」として意味的にまとまって提供 -final class MassMarketOntology implements PricingOntology -{ - // 大衆市場では、高価格は障壁を意味する -} -``` +**価値**: +- **概念的まとまり**: 「ValidatedUserになるには何が必要?」が明確 +- **テストの簡素化**: 存在理由オブジェクト一つをモックすれば済む +- **関心の分離**: 関連する道具が一か所に集約 + +## 委譲による状態実現 -## 複数の文脈的能力 +存在理由層では、オブジェクトが自身の状態実現を存在理由に委譲します: ```php -final class InternationalMessage +final class SavedUser { public function __construct( - #[Input] string $recipientName, - #[Input] string $message, - #[Inject] CulturalEtiquette $culture, // 文化的文脈 - #[Inject] CommunicationProtocol $protocol, // コミュニケーション文脈 - #[Inject] FormalityLevel $formality // 形式レベル文脈 + #[Input] UserData $data, + #[Input] SaveReason $reason // 存在理由を受け取り ) { - $name = $culture->addHonorific($recipientName); - $greeting = $culture->formatGreeting($message); - $styled = $formality->apply($greeting); - - $this->content = $protocol->format($styled); + // 保存処理を存在理由に委譲 + $this->result = $reason->saveUser($data); } } ``` -## 依存性解決 - -依存性注入による文脈認識バインディング: - -```php -$injector->bind(PaymentGateway::class) - ->annotatedWith(Production::class) - ->to(StripeGateway::class); - -$injector->bind(PaymentGateway::class) - ->annotatedWith(Testing::class) - ->to(MockGateway::class); -``` - -## 革命 - -存在理由層は依存性注入を**ツール提供**から**存在論的文脈**に変換します。 +オブジェクト自身は「何になるか」を宣言し、存在理由は「どうやってその状態になるか」を実現します。この分離により、状態定義と実現手段が明確に分けられます。 -オブジェクトは単にサービスを受け取るのではなく、環境に適した**存在の方法**を受け取ります。 +`SavedUser`になるためには保存用の道具セットが、`ValidatedUser`になるためには検証用の道具セットが必要です。存在理由オブジェクトは「この状態になるには何が必要か?」を明確に整理し、単一責任原則に従うため、テストも簡潔になります。 --- -**次へ**: 意味的例外が意味を保持する[エラーハンドリング & 検証](09-error-handling.html)について学びましょう。 +**次へ**: エラーの意味保持について[検証とエラーハンドリング](09-error-handling.html)で学びましょう。 -> 「存在理由層は世界の能力がオブジェクトの性質と出会う場所—意味のある成長のための文脈的条件として。」 +> 「存在理由層は、オブジェクトがその存在様式を実現するために必要な道具セットを提供します。」 diff --git a/manuals/1.0/ja/10-semantic-logging.md b/manuals/1.0/ja/10-semantic-logging.md new file mode 100644 index 0000000..b042423 --- /dev/null +++ b/manuals/1.0/ja/10-semantic-logging.md @@ -0,0 +1,63 @@ +--- +layout: docs-ja +title: "10. 意味的ログ" +category: Manual +permalink: /manuals/1.0/ja/10-semantic-logging.html +--- + +# 意味的ログ + +> 「記録されるものは記憶となり、記憶されるものは真実となる」 +> +>   —オーウェル『1984年』の概念より(1949年) + +## 概要 + +Beフレームワークは、オブジェクトの変容プロセスを構造化されたログとして自動記録する**意味的ログ**機能を実装しています。 + +### 基本コンセプト + +**従来のログ**:イベントの断片的な記録 +**意味的ログ**:オブジェクトの完全な変容ストーリーの記録 + +```php +// オブジェクトの変容が... +#[Be(RegisteredUser::class)] +final class UserInput { /* ... */ } + +final class RegisteredUser { /* ... */ } + +// 自動的に構造化ログとして記録される +{ + "metamorphosis": { + "from": "UserInput", + "to": "RegisteredUser", + // 完全な変容情報... + } +} +``` + +## 技術的基盤 + +[Koriym.SemanticLogger](https://github.com/koriym/Koriym.SemanticLogger)と統合: + +- **型安全な構造化ログ** +- **Open/Event/Close パターン** +- **JSONスキーマ検証** +- **階層的操作追跡** + +## 提供価値 + +### 開発・デバッグ +オブジェクト変容の完全な追跡により、複雑な処理フローの理解と問題特定が容易になります。 + +### 監査・コンプライアンス +すべての変容が構造化データとして記録されるため、完全な監査証跡を提供できます。 + +### システム分析 +オブジェクトの成長パターンと処理効率の分析が可能になります。 + +--- + +**詳細な使用方法、設定例、実践的なサンプルについては、ドキュメントを後日整備します。** + diff --git a/manuals/1.0/ja/12-philosophy-behind.md b/manuals/1.0/ja/12-philosophy-behind.md new file mode 100644 index 0000000..72fd3b4 --- /dev/null +++ b/manuals/1.0/ja/12-philosophy-behind.md @@ -0,0 +1,412 @@ +--- +layout: docs-ja +title: "12. 背後にある哲学" +category: Philosophy +permalink: /manuals/1.0/ja/12-philosophy-behind.html +--- + +# 背後にある哲学 + +> 「万物は流転する」 +> ——ヘラクレイトス(紀元前535-475年) + +Beフレームワークの実装を学んだ今、その根底に流れる深い哲学的洞察を探求しましょう。これは単なる技術的選択ではなく、存在と変容の本質についての古代からの叡智と、現代の計算理論との出会いです。 + +## 1. 存在論的プログラミング:「WHETHER?」の発見 + +### なぜ存在論なのか + +従来のプログラミングは二つの問いに答えてきました: + +- **「何をするか?」(WHAT?)** - 機能とアルゴリズム +- **「どうやるか?」(HOW?)** - 実装とパフォーマンス + +しかし、最も根本的な問いが見過ごされていました: + +- **「そもそも存在できるか?」(WHETHER?)** + +存在論的プログラミングは、この「WHETHER?」を最初に問います。無効なメールアドレスは`$email`として存在できるでしょうか?負の年齢は`$age`として生まれることができるでしょうか? + +```php +// 存在の問い:この状態は可能か? +#[Be(ValidatedUser::class)] // 存在の運命を宣言 +final class UserInput +{ + public function __construct( + public readonly string $email, // 存在条件1 + public readonly int $age // 存在条件2 + ) {} +} + +// 答え:条件が満たされれば ValidatedUser として存在する +``` + +**従来型**:「このデータを検証してください」(命令) +**存在論型**:「このデータは存在できますか?」(存在の問い) + +### AI時代における人間の役割 + +AIが「どうやるか」を最適化できる時代に、人間の役割は「何が存在すべきか」にシフトしていきます。エンジニアは実装者から、定義者に変わるのです。 + +- **人間**:意味の定義、存在の条件の設定 +- **AI**:最適な実現方法の生成 +- **協働**:人間の意味創造 × AIの実装最適化 + +## 2. 時間的存在:ハイデガーの「現存在」をコードで表現 + +### 時間の中に投げ込まれた存在 + +ハイデガーは人間を**被投性(Geworfenheit)**を持つ存在として描きました。私たちは選択できない条件から始まり、そこから自分の存在を築き上げます。 + +Beフレームワークのオブジェクトも同様の構造を持ちます: + +```php +// 被投性:選択できない初期条件 +#[Be(UserProfile::class)] +final class UserInput // 投げ込まれた存在 +{ + public function __construct( + public readonly string $name, // 与えられた条件 + public readonly string $email // 与えられた状況 + ) {} +} + +// 企投性:未来への可能性 +final class UserProfile // 可能性への投企 +{ + public function __construct( + #[Input] string $name, // 被投された過去 + #[Input] string $email, + #[Inject] NameFormatter $formatter // 世界との出会い + ) { + $this->displayName = $formatter->format($name); // 新しい存在 + } + + public readonly string $displayName; +} +``` + +### 現存在としてのオブジェクト + +ハイデガーの**現存在(Dasein)**は、「そこに存在する」という意味で、時間の中で自己を理解する存在です。Beフレームワークのオブジェクトは、まさにこの現存在的性格を持ちます: + +- **時間性**:過去(入力クラス)→現在(存在クラス)→未来(最終オブジェクト) +- **自己理解**:`#[Be()]`による自己の可能性の理解 +- **世界内存在**:`#[Inject]`による世界との関わり +- **実存性**:自らの存在可能性を選択する(型駆動変容) + +```php +// 現存在的オブジェクト:時間の中で自己を理解する +#[Be([ApprovedLoan::class, RejectedLoan::class])] // 存在可能性の理解 +final class LoanApplication +{ + // 自己の運命を決定する実存的選択 + public readonly ApprovedLoan|RejectedLoan $being; + + public function __construct( + #[Input] Money $amount, // 被投された条件 + #[Input] CreditScore $score, // 与えられた状況 + #[Inject] LoanPolicy $policy // 世界との出会い + ) { + // 実存的決断:自分は何者になるか + $this->being = $policy->evaluate($amount, $score) > 0.7 + ? new ApprovedLoan($amount, $score) + : new RejectedLoan($amount, $score); + } +} +``` + +## 3. 道と無為:老子の哲学をプログラミングで実現 + +### 無為自然の原理 + +老子は言いました:「道常無為而無不為」——道は常に無為でありながら、なしえないことはない。 + +これは「何もしない」という意味ではありません。自然の流れに従って、無理に強制することなく、事物の本性に沿って作用することです。 + +```php +// 無為の実践:強制しない、自然に流れる +final class OrderProcessing +{ + public function __construct( + #[Input] Order $order, // 自然な前提 + #[Inject] PaymentGateway $gateway // 外部の力 + ) { + // 無為:何かをさせるのではなく、なるべき姿になることを可能にする + $this->result = $gateway->process($order); // 自然な変容 + } +} + +// これではない(有為:強制的な実行): +// $gateway->validateCard($order->card); +// $gateway->chargeAmount($order->amount); +// $gateway->sendConfirmation($order->email); +``` + +### 水のように流れるコード + +老子はまた言いました:「上善若水」——最高の善は水のようなものです。水は争わず、みんなが嫌がる低いところに身を置き、しかも万物を潤します。 + +Beフレームワークのオブジェクトは水のように流れます: + +- **争わない**:外部制御なし、自己決定による変容 +- **低いところ**:シンプルな構造、複雑さを回避 +- **万物を潤す**:他のオブジェクトの変容を可能にする + +```php +// 水のような自然な流れ +$result = $becoming(new ApplicationInput($data)); + +// オブジェクト自身が次の形を知っている(水が低きに流れるように) +// 外部のオーケストレーターは不要 +``` + +## 4. エンテレケイア:アリストテレスの完全実現 + +### 可能性から現実性への移行 + +アリストテレスの**エンテレケイア(ἐντελέχεια)**は、潜在的なものが現実的になる過程を表します。どんぐりが樫の木になるように、内在的な可能性が外部との相互作用で実現される瞬間です。 + +```php +// エンテレケイア:潜在性の完全実現 +final class MatureUser // 完全実現された存在 +{ + public function __construct( + #[Input] UserData $potentiality, // 潜在性 + #[Inject] ValidationService $actuator // 現実化の力 + ) { + // エンテレケイア:潜在性が現実性へ移行する瞬間 + $this->actualizedProfile = $actuator->actualize($potentiality); + } + + public readonly UserProfile $actualizedProfile; // 現実化された存在 +} +``` + +### コンストラクタは変容の舞台 + +コンストラクタは、エンテレケイアが起こる神聖な場所です。ここで内在的な可能性(`#[Input]`)が外部の現実化する力(`#[Inject]`)と出会い、新しい存在が生まれます。 + +```php +public function __construct( + #[Input] string $name, // 内在的可能性 + #[Inject] Formatter $formatter // 現実化する力 +) { + // エンテレケイア:この瞬間に新しい存在が生まれる + $this->formattedName = $formatter->format($name); +} +``` + +## 5. 充足理由律:ライプニッツの存在理由 + +### すべてのものには存在する理由がある + +ライプニッツの**充足理由律(Principium rationis sufficientis)**は「すべてのものには、それが存在するための十分な理由がある」と述べます。 + +Beフレームワークでは、この哲学が**存在理由層**として実現されています: + +```php +final class ValidatedUser +{ + public function __construct( + #[Input] string $email, // 内在的性質 + #[Input] ValidationReason $reason // 存在理由(raison d'être) + ) { + // ValidationReasonが、ValidatedUserの存在理由を提供 + $this->isValid = $reason->validate($email); + } +} +``` + +### raison d'être(存在理由) + +フランス語の**raison d'être**は「存在する理由」を意味します。存在理由層は、オブジェクトがその存在でいられるための根拠を提供します: + +- `ValidatedUser`の raison d'être → 検証能力 +- `SavedUser`の raison d'être → 保存能力 +- `DeletedUser`の raison d'être → 削除能力 + +各存在には、その存在を可能にする十分な理由があります。 + +## 6. 内在と超越:スピノザの二重のアスペクト + +### 内在的性質と超越的力 + +スピノザは現実を一つの実体の二つのアスペクトとして捉えました:**内在(Immanence)**と**超越(Transcendence)**。 + +```php +final class UserProfile +{ + public function __construct( + #[Input] string $name, // 内在:既に持っているもの + #[Input] string $email, // 内在:与えられた性質 + #[Inject] Formatter $formatter, // 超越:外部からの力 + #[Inject] Validator $validator // 超越:世界が提供する能力 + ) { + // 内在と超越の出会いで新しい存在が生まれる + $this->displayName = $formatter->format($name); // 新しい内在 + $this->isValid = $validator->validate($email); // 新しい内在 + } +} +``` + +### 変容の永遠の公式 + +すべての存在クラスは同じ哲学的構造を持ちます: + +**内在的性質** + **超越的力** → **新しい内在的存在** + +これはスピノザの「神即自然」の思想を反映しています。自然(外部の力)と神性(内在的本質)は一つの現実の二面であり、その相互作用から新しい存在が生まれます。 + +## 7. 荘子の相対性:複数の運命を受け入れる + +### 万物斉同の思想 + +荘子は「万物斉同」を説きました——すべてのものは根本的に同等であり、対立する概念も実は一つの現実の異なる側面に過ぎません。 + +型駆動変容は、この思想を体現しています: + +```php +#[Be([Success::class, Failure::class])] // 成功と失敗は同等の可能性 +final class PaymentAttempt +{ + public readonly Success|Failure $being; // 両方とも有効な存在 + + public function __construct(/* ... */) { + // 成功も失敗も、どちらも完全な存在として扱われる + $this->being = $result->isSuccessful() + ? new Success($result) // 成功という存在 + : new Failure($result); // 失敗という存在 + } +} +``` + +## 8. ヘラクレイトスの流転:永続的な変化 + +### 「万物は流転する」 + +ヘラクレイトスは「パンタ・レイ」(πάντα ῥεῖ)——「万物は流転する」と言いました。同じ川に二度入ることはできません。なぜなら、それはもはや同じ川ではないし、あなたも同じ人間ではないからです。 + +メタモルフォーシスは、この永続的変化を表現します: + +```php +// 時間 T0: 原初の存在 +#[Be(EmailValidation::class)] +final class EmailInput { /* ... */ } + +// 時間 T1: 第一変容(T0は既に過去) +#[Be(UserCreation::class)] +final class EmailValidation { /* ... */ } + +// 時間 T2: 最終存在(すべての過去を内包) +final class UserCreation { /* ... */ } +``` + +各瞬間は二度と戻らず、オブジェクトは時間の流れの中で自然に変容していきます。 + +### 対立の統一 + +ヘラクレイトスはまた「対立物の統一」を説きました。昼と夜、生と死、上と下——対立するものは実は一つの現実の異なる側面です。 + +```php +// 対立の統一:活性化と非活性化は同じ現実の両面 +public readonly ActiveUser|InactiveUser $being; +``` + +## 9. 仏教の縁起:相互依存の存在 + +### 諸法無我と縁起 + +仏教の**縁起(pratītyasamutpāda)**は「すべてのものは相互に依存して存在する」という教えです。独立した実体は存在せず、すべては関係性の網の中で生まれます。 + +Beフレームワークのオブジェクトは、まさにこの縁起的存在です: + +```php +final class UserProfile // 縁起的存在 +{ + public function __construct( + #[Input] string $name, // 他の存在に依存 + #[Inject] DatabaseConnection $db, // 外部との関係に依存 + #[Inject] ValidationService $validator // サービスとの相互依存 + ) { + // 相互依存の関係から新しい存在が現れる + } +} +``` + +### 無我の実装 + +仏教の**無我(anātman)**は「固定した自己は存在しない」という教えです。すべては変化する関係性の束です。 + +Beフレームワークでは: +- オブジェクトに固定した「本質」はありません +- `public readonly` により状態は変化しません +- 各段階は完全に独立した存在として現れます +- 「自己」は関係性(依存性注入)によって構成されます + +## 10. プログラミング哲学の統合 + +### 東洋と西洋の叡智 + +Beフレームワークは、東洋と西洋の哲学的伝統を統合します: + +**東洋の叡智**: +- **道教**:無為自然の流れ +- **仏教**:縁起と無我、諸行無常 +- **荘子**:相対性と変容の受容 + +**西洋の思想**: +- **ハイデガー**:時間的存在としての現存在 +- **アリストテレス**:エンテレケイア(可能性の実現) +- **ライプニッツ**:充足理由律 +- **スピノザ**:内在と超越の統一 + +### 計算哲学への昇華 + +これらの古代の叡智が現代のプログラミングで実現されるとき、新しい**計算哲学**が生まれます: + +- **存在論的設計**:何が存在できるかを定義する +- **時間的プログラミング**:オブジェクトの時間性を尊重する +- **無為的実行**:自然な流れに従う制御 +- **縁起的依存性**:相互依存を通した存在の実現 +- **相対主義的結果**:複数の有効な結果を受け入れる + +## 11. 未来への展望:プログラミングの次なる進化 + +### パラダイムの進化 + +プログラミングパラダイムの進化を見ると、私たちは徐々に自然の原理に近づいています: + +1. **機械語時代**:「機械に命令する」 +2. **手続き型時代**:「手順を記述する」 +3. **オブジェクト指向時代**:「オブジェクトに責任を委譲する」 +4. **関数型時代**:「数学的変換を定義する」 +5. **存在論的時代**:「存在の条件を宣言し、自然な変容を可能にする」 + +### AI時代の人間性 + +AIが「どうやるか」を最適化できる時代に、人間の独自性は「何が存在すべきか、何に意味があるか」を決める能力にあります。 + +存在論的プログラミングは、この人間固有の価値を最大化します: +- **意味の創造者**:どんな存在に価値があるかを決定 +- **存在の設計者**:可能な存在状態を定義 +- **哲学的思考者**:システムの存在論的構造を設計 + +### AI時代のプログラミングパラダイム + +AIが「どうやるか」の実装を担える時代では、プログラミングの本質が変わります。命令を記述することよりも、**何が存在できるか**を定義することが中核となります。 + +存在論的プログラミングは、この新しい時代のための哲学的基盤を持つパラダイムです: +- AIが最適化できる実装の詳細よりも +- 人間が定義すべき存在の意味と制約に焦点を当てる +- 「命令の書き手」から「存在の設計者」への役割転換を可能にする + +--- + +> **「川の流れるところに道がある」** +> ——老子の言葉の現代的解釈 + +Beフレームワークは、古代の叡智と現代の技術が出会う場所です。ここでは、コードが哲学となり、プログラミングが存在論となり、エンジニアが現代の哲学者となります。 + +オブジェクトが自然に流れ、変容し、そしてあるべき姿になる——これが、Beフレームワークが体現する、プログラミングの新しい可能性です。 +```