Datetimeimmutable

/ Comments off

Bug #78751: serialize converts DateTimeImmutable to DateTime when serialising DatePeriod: Submitted: 2019-10-25 11:32 UTC: Modified: 2019-11-28 22:27 UTC. In PHP 5.5 the DateTimeImmutable class was introduced. Immutable objects are nice in that they can not be modified, which helps reduce the likelihood I make certain types of errors.

  • PHP Tutorial
  • Advanced PHP
  • PHP Form Examples
  • PHP login Examples

DateTime VS DateTimeImmutable example. GitHub Gist: instantly share code, notes, and snippets.

  • PHP AJAX Examples
  • PHP XML Example
  • PHP Frame Works

Datetimeimmutable Settimezone

  • PHP Design Patterns
  • PHP Function Reference
  • PHP Useful Resources
  • Selected Reading

Definition and Usage

The date_create_immutable() is an alias of DateTimeImmutable::__construct(). This function accepts a date/time string and a time zone as parameters (optional) an creates a DateTimeImmutable object.

Unlike DateTime object, this object does not allows any modifications, it creates a new object in case of changes and returns it. By default, this function creates an object of the current date/time

Syntax

Parameters

Sr.NoParameter & Description
1

date_time (Optional)

This is the date/time string (in supported formats) for which you need to create an immutable DateTime object.

2

timezone (Optional)

This represents the timezone of the given time.

Return Values

PHP date_create_immutable() function returns the created DateTimeImmutable object.

PHP Version

This function was first introduced in PHP Version 5.5.0 and, works with all the later versions.

Example

Following example demonstrates the usage of the date_create_immutable() function −

This will produce following result −

Example

Following is an example of date_create_immutable() with timezone parameter −

This will produce following result −

Example

In the following example we have created a immutable date and normal date objects added intervals to them and displayed the resultant values. Since immutable DateTime object creates and returns a new object in case of an attemt to change, you cans observe that its vary before and after change −

This will produce following result −

last modified July 5, 2020

Datetime

PHP Monolog tutorial shows how to do logging in PHP with Monolog.

Logging

Logging is the process of writing information into log files. Log filescontain information about various events that happened in operating system, software, orin communication.

Purpose of logging

Logging is done for the following purposes:

  • Information gathering
  • Troubleshooting
  • Generating statistics
  • Auditing
  • Profiling

Logging is not limited to identifying errors in software development. It is also usedin detecting security incidents, monitoring policy violations, providing information in caseof problems, finding application bottlenecks, or generating usage data.

Events to log

Events that should be logged include input validation failures, authenticationand authorization failures, application errors, configuration changes, andapplication start-ups and shut-downs.

Events not to log

Events that should not be logged include application source code, sessionidentification values, access tokens, sensitive personal data, passwords,database connection strings, encryption keys, bank account and card holder data.

Logging best practices

The following are some best practices for logging:

  • Logging should be meaningful.
  • Logging should contain context.
  • Logging should be balanced; it should not include too little or too much information.
  • Logging messages should be understandable to humans and parseable by machines.
  • Logging should structured and done at different levels.
  • Logging should be adapted to development and to production.
  • Logging in more complex applications should be done into several log files.

PHP Monolog

Monolog is a popular PHP logging library. It allows to sendlogs to files, sockets, inboxes, databases and various web services.It implements the PSR-3 interface.

We install Monolog with composer.

Monolog structure

A Monolog logger instance has a channel (name) and a stack of handlers.The handlers are responsible for saving the message to the file, database,or sending it to a mail.

A logged message travels through the handler stack. The last handler actsfirst. The further propagation of a message is controlled with the bubblevariable, which is by default set to true.

A message record is a piece of information that is going to be writtento the log. The message record has the the following parts:

KeyTypeDescription
messagestringThe log message.
levelintSeverity of the log message.
level_namestringString representation of log level.
contextarrayArbitrary data passed with the construction of the message.
channelstringThe channel this message was logged to.
datetimeMonologDateTimeImmutableDate and time when the message was logged.
extraarrayA placeholder array where processors can put additional data.

A processor is any PHP callable that can be used to process thelog message. It can add some extra data to the record.

The context is array data which has additional information thatdoes not fit well in the primary string. The context is a parameter to thelogging methods (e.g. info() or warn()).

Formatters are used to format message records.

Monolog log levels

Logging levels are used to categorize log messages by urgency.Monolog has the following log levels:

  • DEBUG - detailed debug information
  • INFO - interesting events
  • NOTICE - normal but significant events
  • WARNING - exceptional occurrences that are not errors
  • ERROR - runtime errors that do not require immediate action
  • CRITICAL - critical conditions
  • ALERT - events for which action must be taken immediately
  • EMERGENCY - emergency events

Less severe logs are not processed by handlers with more severe logging levels.By setting the log level to ERROR we get messages with ERROR level and up.

Each handler is specified a log level; the default is DEBUG.To produce a message with a specific log level, we have methods includinginfo(), warn(), error(), andcritical(). Since Monolog predates PSR-3, it containsduplicate methods (e.g. addInfo() or addWarning()).

Monolog simple example

In the first example, we use Streamhandler to loga message to a file.

The example writes an info message to the logs/app.log file. Adobe captivate crack mac.

A new logger named main is created.

We add a StreamHandler to the logger with pushHandler().The handler writes messages to the specified file with the DEBUG severity.

We log an info message with info() method.

This is the written message. The log message starts with the currentdatetime. It is followed by the log channel name and level. Thencomes the message record. The two pairs of square brackets iswhere we can specify context and extra data. We can customize thisoutput with Monolog formatters.

Monolog console logging

We can write log messages to terminal.

console_log.php

We write to console by specifying php://stderr to the StreamHandler.

Monolog context array

Monolog context array allows to add information to the message recordsat the userland level.

The second parameter of the info() method is the context array.We add the current user to the message.

This is the output.

Monolog logger handler stack

We can add multiple handlers to the stack. The last added handler isexecuted first.

handler_stack.php

In the example, we have two logger handlers: a file and a consolehandler. If we change the $bubble to false,the message will not be written to the logs/app.log file.

Monolog custom processor

A custom processor can be added with pushProcessor().

In the example, we add some extra information to the message recordin the processor. According to the documentation, the difference betweencontext and extra data is that context is supplied in user land whereasextra is internal only and can be filled by processors.

The extra information is added at the end of the output.

Monolog JsonFormatter

JsonFormatter writes records in JSON format.

json_formatter.php

The example writes an info message to a file in JSON format using JsonFormatter.

This is the logged message.

Monolog LineFormatter

LineFormatter formats a log record into a one-line string.

In the example, we customize the message record with LineFormatter.

We create a custom record message. It contains datetime, channel name, level name,message and context data.

We add the formatter to the handler with setFormatter().

This is a sample output.

Monolog mail log message

Php8.0

Emails can be sent with SwiftMailerHandler

For this example, we need to install swiftmailer/swiftmailerpackage.

Note: Gmail is not ideal for testing applications. Weshould use an online service such as Mailtrap or Mailgun, or use an SMTPserver provided by a webhosting company.

In our example, we use Mailtrap service.

In the example, we use the SwiftMailerHandler to send a message record to a mail inbox.

Using the Mailtrap connection details, we build the transporter.

A Swinf_Mailer is created.

Docker Php8

A Swift_Message is created. It contains the fromthe to fields.

We add the SwiftMailerHandler to the logger and createa critical message with critical().

Php8

In this tutorial, we have used Monolog to do logging in PHP.

Datetimeimmutable Modify

List all PHP tutorials.