AthenaeumAthenaeum
Packages
  • next
  • current
  • v9.x
  • v8.x
  • v7.x
  • v6.x
  • v5.x
  • v4.x
  • v3.x
  • v2.x
  • v1.x
Changelog
GitHub
Packages
  • next
  • current
  • v9.x
  • v8.x
  • v7.x
  • v6.x
  • v5.x
  • v4.x
  • v3.x
  • v2.x
  • v1.x
Changelog
GitHub
  • Version 7.x

    • Release Notes
    • Upgrade Guide
    • New to this...
    • Contribution Guide
    • Security Policy
    • Code of Conduct
    • Origin
  • ACL

    • Introduction
    • How to install
    • Setup
    • Permissions
    • Roles
    • Users
    • Cached Permissions
  • Antivirus

    • Introduction
    • How to install
    • Setup
    • How to use
    • Scanners

      • Introduction
      • ClamAV
      • Null
      • Custom
    • Events
    • PSR
  • Audit

    • Audit
    • How to install
    • Setup
    • Recording
    • Events
  • Auth

    • Introduction
    • How to install
    • Fortify

      • Prerequisites
      • Actions

        • Rehash Password
  • Circuits

    • Circuits
    • How to install
    • Setup
    • Usage
    • Events
  • Collections

    • Collections
    • How to install
    • Summation

      • Summation Collection
      • Items Processor
  • Config

    • Configuration Loader
    • How to install
    • Setup
    • Load Configuration Files
    • Custom File Parsers
  • Console

    • Command and Schedule Registration
    • How to install
    • Setup
    • Commands
    • Schedules
  • Container

    • IoC Service Container
    • How to install
    • Container
    • List Resolver
  • Core

    • Athenaeum Core Application
    • How to install
    • Setup
    • Usage

      • Configuration
      • Service Providers
      • Service Container
      • Events
      • Caching
      • Logging
      • Console
      • Task Scheduling
      • Exception Handling
      • Extending Core Application
      • Testing
  • Database

    • Introduction
    • How to install
    • Models

      • Instantiatable
      • Sluggable
    • Query

      • Criteria (Query Filter)
  • Dto

    • Data Transfer Object (DTO)
    • How to install
    • Create Interface
    • Implement DTO
    • How to use
    • Populate
    • Export
    • Json
    • Serialization
    • Nested DTOs
    • Array DTO
  • ETags

    • Introduction
    • How to install
    • Setup
    • ETags usage

      • How to use
      • Generators

        • Default Generator
        • Custom Generator
      • Eloquent Models
    • Http Request Preconditions

      • Introduction
      • Resource Context
      • Preconditions
      • Actions
      • RFC 9110

        • If-Match
        • If-Unmodified-Since
        • If-None-Match
        • If-Modified-Since
        • If-Range
      • Extensions

        • Introduction
        • Range
      • Range Validator
      • Download Stream
    • Macros
  • Events

    • Register Listeners and Subscribers
    • How to install
    • Setup
    • Listeners
    • Subscribers
  • Filters

    • Search Filter Utilities
    • Prerequisites
    • How to install
    • Setup
    • Processor
    • Filters Builder
    • Predefined Resources

      • Search Processor
      • Sorting Processor
      • Constraints Processor
      • Matching Processor
    • Tip: Create a base builder
  • Flysystem

    • Introduction
    • Database Adapter

      • Introduction
      • How to install
      • Setup
      • Data Deduplication
      • MIME-Type Detection
  • Http

    • Api

      • Http API
      • How to install
      • Setup
      • Resources

        • Introduction
        • Timestamps
        • Self-Link
        • Relations
        • Caching
        • Registrar
      • Requests

        • Introduction
        • List Resources
        • List Deleted
        • Show Resource
        • Create Resource
        • Update Resource
        • Delete Resource
        • List Related
        • Process Multiple Resources
        • Helpers
      • Middleware

        • Introduction
        • Request Must Be Json
        • Capture Fields To Select
        • Remove Response Payload
    • Clients

      • Http Clients
      • How to install
      • Setup
      • Basic Usage
      • Available Methods

        • Fluent Api
        • Protocol Version
        • Base Uri
        • Http Method and Uri
        • Headers
        • Accept & Content-Type
        • Authentication
        • Http Query
        • Payload Format
        • Payload
        • Attachments
        • Cookies
        • Response Expectations
        • Middleware
        • Conditions
        • Criteria
        • Redirects
        • Timeout
        • Debugging
        • Logging
        • Driver Options
        • Driver
      • Http Query Builder

        • Introduction
        • Select
        • Where
        • Dates
        • Include
        • Pagination
        • Sorting
        • Raw Expressions
        • Custom Grammar
    • Cookies

      • Http Cookies
      • How to install
      • Usage
    • Messages

      • Http Messages
      • How to install
      • Serializers
  • Maintenance

    • Modes

      • Maintenance Modes
      • How to install
      • Setup
      • Basic Usage
      • Available Drivers
  • Mime Types

    • MIME-Types
    • How to install
    • Setup
    • Usage
    • Drivers

      • Available Drivers
      • File Info
  • Properties

    • Properties Overload
    • How to install
    • Usage
    • Naming Convention
    • Properties Visibility
  • Redmine

    • Redmine Api Client
    • How to install
    • Setup
    • General Usage

      • Supported Operations
      • Fetch list of resources
      • Find
      • Fetch
      • Create new record
      • Update existing record
      • Delete existing record
      • Relations
    • Available Resources

      • Predefined Resources
      • Attachments
      • Enumerations
      • Issue Relations
      • Users
      • User Groups
      • Roles
      • Project Memberships
      • Versions (Milestones)
      • Issue Categories
      • Trackers
  • Service

    • Service Registrar
    • How to install
    • How to use
  • Streams

    • Streams
    • How to install
    • Setup
    • How to use

      • Introduction
      • Open and Close
      • Raw Resource
      • Seeking
      • Reading
      • Writing
      • Size
      • Truncate
      • Sync
      • Flush
      • Hash
      • MIME-Type
      • Filename
      • Output
      • Locking
      • Transactions
      • Meta
      • Misc
  • Support

    • Introduction
    • How to install
    • Laravel Aware-of Helpers

      • How to use
      • Enforce Via Interface
      • Custom Default
      • Pros and Cons
      • Available Helpers
    • Aware-of Properties

      • Generator
      • Available Aware-of Helpers
    • Live Templates
  • Testing

    • Introduction
    • How to install
    • Test Cases
    • Testing Aware-of Helpers
  • Translation

    • Introduction
    • How to install
    • Exporters

      • Introduction
      • Setup
      • How to use
      • Drivers

        • Introduction
        • Array
        • Lang.js (Array)
        • Lang.js (JSON)
        • Cache
  • Utils

    • Introduction
    • How to install
    • Array
    • Duration
    • Json
    • Math
    • Memory
    • Method Helper
    • Invoker
    • Populatable
    • String
    • Version
  • Validation

    • Introduction
    • How to install
    • Setup
    • Rules

      • Alpha-Dash-Dot
      • Date Format
      • Semantic Version
You are viewing documentation for an outdated version. It is no longer supported!

Open and Close

  • How to open
    • File
    • Memory
    • Temporary
    • Existing resource
    • Existing PSR-Stream
    • SplFileInfo
    • PSR Uploaded File
    • Lazy
    • Cloning
  • How to close
    • Close stream
    • Detaching resource

How to open

File

Use the open() method to open a stream to a file or URL.

use Aedart\Streams\FileStream;

$stream = FileStream::open('recipients.txt', 'r+b');

Behind the scene, PHP's fopen() is used.

Memory

To open a stream to php://memory, use the openMemory() method.

$stream = FileStream::openMemory();

See PHP Documentation for additional details.

Temporary

You may also open a stream to php://temp, by using openTemporary()

$stream = FileStream::openTemporary();

To specify the maximum memory limit, before PHP's internal mechanisms write to a physical file, use the 2nd argument.

$stream = FileStream::openTemporary('r+b', 5 * 1024 * 1024);

See PHP Documentation for additional details.

Existing resource

If you already have an existing resource to a file or URL, you can "wrap" it into a stream component, by using the make() method.

$resource = fopen('team.txt', 'w+b');

// ...Later in your application...
$stream = Stream::make($resource);

Existing PSR-Stream

Use the makeFrom() method when you need to wrap an existing StreamInterface component.

$stream = Stream::makeFrom($psrStream);

Warning

The makeFrom() will automatically detach the given StreamInterface component's underlying resource. This means that you will no longer be able to use the provided PSR stream instance.

SplFileInfo

Available since v7.4.x

When working with uploaded files, e.g. from Laravel or Symfony (SplFileInfo instances), then you can open a file stream using the openFileInfo() method.

$stream = FileStream::openFileInfo($uploadedFile, 'r');

Filename

For Laravel and Symfony, the uploaded file's getClientOriginalName() return value is used as the stream's filename() value.

PSR Uploaded File

Available since v7.4.x

You may also create a file stream instance for an existing PSR-7 Uploaded File instance, using the openUploadedFile() method.

$stream = FileStream::openUploadedFile($psrUploadedFile);

Warning

Unless specified otherwise, the openUploadedFile() method will automatically detach the uploaded file's underlying stream. If you wish to avoid this, then set the $asCopy argument to true (defaults to false).

// Copies the PSR stream into the file stream...
$stream = FileStream::openUploadedFile(
    file: $psrUploadedFile,
    asCopy: true
);

For more information, see the source code of openUploadedFile() and see also copy from documentation.

Filename

The uploaded file's getClientFilename() return value is used as the stream's filename() value.

Lazy

Lastly, you may also open a stream after you have created a Stream or FileStream, using a callback. The openUsing() accepts a callback, which must return a valid resource of the type "stream".

use Aedart\Streams\FileStream;

$stream = new FileStream();

// ...later in your application...
$stream->openUsing(function() {
    return fopen('countries.txt', 'rb');
});

Info

openUsing() will fail if the stream instance already has a valid resource specified (when the stream is already open). Use the isOpen() method to determine if a stream can be opened.

if (!$stream->isOpen()) {
    $stream->openUsing(function() {
        return fopen('countries.txt', 'rb');
    });
} else {
    // ...do something else...
}

Cloning

Not supported

Cloning an existing stream instance is not supported and will result in StreamException to be thrown.

$stream = FileStream::open('locations.txt', 'r');
$clone = clone $stream; // Fails - StreamException is thrown!

How to close

Close stream

When you need to close a stream, invoke the close() method. The underlying resource will be detached and closed using PHP's fclose().

$stream->close();

Detaching resource

If you do not wish to close the stream, but you want to detach - to separate the underlying resource, from the stream instance, then you can use the detach() method.

$resource = $stream->detach();

// ...stream instance is now useless!

Caution

When you detach the underlying resource from the stream, the stream instance becomes useless. You SHOULD avoid reusing or reopening a resource, when such is the case.

Not recommended

The following example is NOT recommended (even though it is possible)!

$resource = $stream->detach();

// ...later... attempt to re-open using same resource
// and same stream instance - NOT RECOMMENDED!
$stream->openUsing(fn () => $resource);

Future versions of Stream and FileStream may prohibit this behaviour.

Edit page
Last Updated: 18/03/2024, 10:45
Contributors: Alin Eugen Deac, alin
Prev
Introduction
Next
Raw Resource