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
- 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
|Sr.No||Parameter & Description|
This is the date/time string (in supported formats) for which you need to create an immutable DateTime object.
This represents the timezone of the given time.
PHP date_create_immutable() function returns the created DateTimeImmutable object.
This function was first introduced in PHP Version 5.5.0 and, works with all the later versions.
Following example demonstrates the usage of the date_create_immutable() function −
This will produce following result −
Following is an example of date_create_immutable() with timezone parameter −
This will produce following result −
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
PHP Monolog tutorial shows how to do logging in PHP with Monolog.
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
- Generating statistics
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.
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.
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
A message record is a piece of information that is going to be writtento the log. The message record has the the following parts:
|message||string||The log message.|
|level||int||Severity of the log message.|
|level_name||string||String representation of log level.|
|context||array||Arbitrary data passed with the construction of the message.|
|channel||string||The channel this message was logged to.|
|datetime||MonologDateTimeImmutable||Date and time when the message was logged.|
|extra||array||A 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.
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.
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 including
critical(). Since Monolog predates PSR-3, it containsduplicate methods (e.g.
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
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.
We write to console by specifying
php://stderr to the
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.
In the example, we have two logger handlers: a file and a consolehandler. If we change the
false,the message will not be written to the
Monolog custom processor
A custom processor can be added with
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.
JsonFormatter writes records in JSON format.
The example writes an info message to a file in JSON format using
This is the logged message.
LineFormatter formats a log record into a one-line string.
In the example, we customize the message record with
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
This is a sample output.
Monolog mail log message
Emails can be sent with
For this example, we need to install
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.
Swinf_Mailer is created.
Swift_Message is created. It contains the fromthe to fields.
We add the
SwiftMailerHandler to the logger and createa critical message with
In this tutorial, we have used Monolog to do logging in PHP.
List all PHP tutorials.