一文帶你吃透什么是PHP中的序列化
1. php 中的序列化
在 PHP 中,序列化是將數(shù)據(jù)結(jié)構(gòu)或?qū)ο筠D(zhuǎn)換為可以存儲或傳輸?shù)淖址硎镜倪^程,經(jīng)過序列化之后的對象或者數(shù)據(jù)結(jié)構(gòu),就可以保存到數(shù)據(jù)庫、緩存或通過網(wǎng)絡(luò)連接發(fā)送它,然后后面從序列化字符串重新創(chuàng)建對象或數(shù)據(jù)結(jié)構(gòu)。
以下是如何在 PHP 中序列化對象的例子:
class User
{
public $name;
public $email;
?
public function __construct($name, $email)
{
$this->name = $name;
$this->email = $email;
}
}
?
$user = new User('John', 'john@example.com');
?
$serializedUser = serialize($user);
?
echo $serializedUser;
此代碼的輸出將是$user對象的字符串表示形式,類似于:
O:4:"User":2:{s:4:"name";s:4:"John";s:5:"email";s:17:"john@example.com";}
PHP 中的序列化格式相當(dāng)簡單。序列化字符串由一系列數(shù)據(jù)類型和值組成,每個數(shù)據(jù)類型和值由冒號分隔。例如,整數(shù)的序列化字符串為i:123,而字符串的序列化字符串為s:5:"Hello"。
要將此字符串反序列化回其原始形式,可以使用以下unserialize()函數(shù):
$unserializedUser = unserialize($serializedUser); ? echo $unserializedUser->name; // John echo $unserializedUser->email; // john@example.com
2. 序列化和反序列化過程中的鉤子
PHP 中有兩個鉤子可用于與此過程進(jìn)行交互。你可以在一個類中定義這些鉤子函數(shù),它會在你序列化或者反序列化對象的時候自動調(diào)用。這對于在序列化或取反列化對象時執(zhí)行自定義操作很有用,例如記錄或驗(yàn)證。
__sleep() 鉤子:這個鉤子在序列化時被調(diào)用。在對象的屬性被序列化之前,它允許開發(fā)人員指定哪些屬性應(yīng)該被序列化,哪些屬性不被序列化。
class MyClass
{
private $data;
private $secret;
?
public function __sleep() {
return ['data'];
}
}
__wakeup() 鉤子:這個鉤子在反序列化時被調(diào)用。在對象的屬性被反序列化之后,它允許開發(fā)人員在對象被反序列化后對其執(zhí)行任何必要的初始化或設(shè)置。
class MyClass
{
private $data;
private $secret;
?
public function __wakeup() {
$this->secret = '123456';
}
}3. 如何使用序列化與外部服務(wù)通信
要使用序列化與外部服務(wù)通信,可以使用 PHP 的內(nèi)置函數(shù)來發(fā)送 HTTP 請求,例如file_get_contents()或curl_exec(),然后你可以將序列化數(shù)據(jù)作為請求中的參數(shù)傳遞,外部服務(wù)可以在其端反序列化數(shù)據(jù)以訪問信息。
下面是使用序列化將數(shù)據(jù)發(fā)送到外部服務(wù)的示例:
$data = [
"name" => "John",
"age" => 30
];
?
// Serialize the data
$serializedData = serialize($data);
?
// Send the serialized data to the external service using HTTP POST
$ch = curl_init("http://example.com/service");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "data=" . $serializedData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
?
// Handle the response from the service
echo $response;
在外部服務(wù)上,您可以使用該unserialize()函數(shù)將序列化數(shù)據(jù)轉(zhuǎn)換回 PHP 數(shù)據(jù)結(jié)構(gòu)或?qū)ο蟆?/p>
// Get the serialized data from the HTTP POST request $serializedData = $_POST['data']; ? // Unserialize the data $data = unserialize($serializedData); ? // Use the data echo "Name: " . $data['name'] . "\n"; echo "Age: " . $data['age'] . "\n";
4. 序列化實(shí)例 - Laravel Queue
當(dāng) Laravel 將 Job 類存儲到隊(duì)列服務(wù)(可以是 Redis、AWS SQS 或類似的服務(wù))中時,對象被序列化。當(dāng)你在 Laravel 中創(chuàng)建一個新的 Job 類時,它附帶了 SerializesModels 特性。
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
?
class ExampleJob implements ShouldQueue
{
use Dispatchable;
use InteractsWithQueue;
use Queueable;
use SerializesModels;
?
/**
* Create a new job instance.
*
* @return void
*/
public function __construct()
{
//
}
?
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
//
}
}如果你的作業(yè)類包含對 Eloquent 模型的引用,這個特性允許你自定義序列化過程。它包含上面看到的鉤子的實(shí)現(xiàn):
namespace Illuminate\Queue;
?
trait SerializesModels
{
use SerializesAndRestoresModelIdentifiers;
?
/**
* Prepare the instance for serialization.
*
* @return array
*/
public function __sleep()
{
// ...
}
?
/**
* Restore the model after serialization.
*
* @return void
*/
public function __wakeup()
{
// ...
}
?
/**
* Prepare the instance values for serialization.
*
* @return array
*/
public function __serialize()
{
// ...
}
?
/**
* Restore the model after serialization.
*
* @param array $values
* @return void
*/
public function __unserialize(array $values)
{
// ...
}
}如Laravel 文檔中所述:
如果你的排隊(duì)作業(yè)在其構(gòu)造函數(shù)中接受 Eloquent 模型,則只有模型的標(biāo)識符將被序列化到隊(duì)列中。當(dāng)實(shí)際處理作業(yè)時,隊(duì)列系統(tǒng)將自動從數(shù)據(jù)庫中重新檢索完整的模型實(shí)例及其加載的關(guān)系。這種模型序列化方法允許將更小的作業(yè)有效負(fù)載發(fā)送到您的隊(duì)列驅(qū)動程序。
5. 最后
serialize()并且unserialize() 是 PHP 的默認(rèn)序列化技術(shù)。事實(shí)上,其他編程語言中有許多庫允許你根據(jù) PHP 標(biāo)準(zhǔn)序列化對象和數(shù)據(jù)結(jié)構(gòu),例如 Java 中的這個庫:
github.com/marcospassos/java-php-serializer
除了這種特定格式,您還可以使用 JSON 標(biāo)準(zhǔn)將數(shù)據(jù)傳輸?shù)酵獠糠?wù)。PHP 通過兩個函數(shù)支持這種序列化:json_encode和json_decode。
到此這篇關(guān)于一文帶你吃透什么是PHP中的序列化的文章就介紹到這了,更多相關(guān)PHP序列化內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
ThinkPHP利用PHPMailer實(shí)現(xiàn)郵件發(fā)送實(shí)現(xiàn)代碼
本文章介紹了關(guān)于在thinkphp中利用了phpmailer來實(shí)現(xiàn)郵件發(fā)送的詳細(xì)教程,有需要的朋友可以參考一下2013-09-09
thinkphp5.1的model模型自動更新update_time字段實(shí)例講解
這篇文章主要介紹了thinkphp5.1的model模型自動更新update_time字段實(shí)例講解,文章代碼示例比較簡單實(shí)用,有正在學(xué)習(xí)tp的同學(xué)可以跟著小編好好閱讀下2021-03-03
laravel-admin 添加、編輯按鈕支持?jǐn)y帶參數(shù)的解決方法
通過修改源碼實(shí)現(xiàn)laravel-admin添加、編輯按鈕支持?jǐn)y帶參數(shù),解決一些特殊功能需求,并且不影響之前添加和編輯程序運(yùn)行,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友參考下吧2023-11-11
php讀取csv實(shí)現(xiàn)csv文件下載功能
用PHP代碼下載CSV文件,可以是字符串,也可以是一個CSV文件,下面直接上代碼2013-12-12
Laravel中基于Artisan View擴(kuò)展包創(chuàng)建及刪除應(yīng)用視圖文件的方法
這篇文章主要介紹了Laravel中基于Artisan View擴(kuò)展包創(chuàng)建及刪除應(yīng)用視圖文件的方法,簡單分析了Laravel擴(kuò)展包的安裝及視圖的創(chuàng)建與刪除操作相關(guān)技巧,需要的朋友可以參考下2016-10-10
codeigniter集成ucenter1.6雙向通信的解決辦法
用codeigniter開發(fā)一個子網(wǎng)站,之后想和原來的論壇進(jìn)行同步,包括同步登陸和雙向通信。這篇文章主要介紹了codeigniter集成ucenter1.6雙向通信的解決辦法,需要的朋友可以參考下2014-06-06

