一文帶你吃透什么是PHP中的序列化
目錄
- 1. php 中的序列化
- 2. 序列化和反序列化過(guò)程中的鉤子
- 3. 如何使用序列化與外部服務(wù)通信
- 4. 序列化實(shí)例 - Laravel Queue
- 5. 最后
1. php 中的序列化
在 PHP 中,序列化是將數(shù)據(jù)結(jié)構(gòu)或?qū)ο筠D(zhuǎn)換為可以存儲(chǔ)或傳輸?shù)淖址硎镜倪^(guò)程,經(jīng)過(guò)序列化之后的對(duì)象或者數(shù)據(jù)結(jié)構(gòu),就可以保存到數(shù)據(jù)庫(kù)、緩存或通過(guò)網(wǎng)絡(luò)連接發(fā)送它,然后后面從序列化字符串重新創(chuàng)建對(duì)象或數(shù)據(jù)結(jié)構(gòu)。
以下是如何在 PHP 中序列化對(duì)象的例子:
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
對(duì)象的字符串表示形式,類(lèi)似于:
O:4:"User":2:{s:4:"name";s:4:"John";s:5:"email";s:17:"john@example.com";}
PHP 中的序列化格式相當(dāng)簡(jiǎn)單。序列化字符串由一系列數(shù)據(jù)類(lèi)型和值組成,每個(gè)數(shù)據(jù)類(lèi)型和值由冒號(hào)分隔。例如,整數(shù)的序列化字符串為i:123
,而字符串的序列化字符串為s:5:"Hello"
。
要將此字符串反序列化回其原始形式,可以使用以下unserialize()
函數(shù):
$unserializedUser = unserialize($serializedUser); ? echo $unserializedUser->name; // John echo $unserializedUser->email; // john@example.com
2. 序列化和反序列化過(guò)程中的鉤子
PHP 中有兩個(gè)鉤子可用于與此過(guò)程進(jìn)行交互。你可以在一個(gè)類(lèi)中定義這些鉤子函數(shù),它會(huì)在你序列化或者反序列化對(duì)象的時(shí)候自動(dòng)調(diào)用。這對(duì)于在序列化或取反列化對(duì)象時(shí)執(zhí)行自定義操作很有用,例如記錄或驗(yàn)證。
__sleep() 鉤子:這個(gè)鉤子在序列化時(shí)被調(diào)用。在對(duì)象的屬性被序列化之前,它允許開(kāi)發(fā)人員指定哪些屬性應(yīng)該被序列化,哪些屬性不被序列化。
class MyClass { private $data; private $secret; ? public function __sleep() { return ["data"]; } }
__wakeup() 鉤子:這個(gè)鉤子在反序列化時(shí)被調(diào)用。在對(duì)象的屬性被反序列化之后,它允許開(kāi)發(fā)人員在對(duì)象被反序列化后對(duì)其執(zhí)行任何必要的初始化或設(shè)置。
class MyClass { private $data; private $secret; ? public function __wakeup() { $this->secret = "123456"; } }
3. 如何使用序列化與外部服務(wù)通信
要使用序列化與外部服務(wù)通信,可以使用 PHP 的內(nèi)置函數(shù)來(lái)發(fā)送 HTTP 請(qǐng)求,例如file_get_contents()
或curl_exec()
,然后你可以將序列化數(shù)據(jù)作為請(qǐng)求中的參數(shù)傳遞,外部服務(wù)可以在其端反序列化數(shù)據(jù)以訪問(wèn)信息。
下面是使用序列化將數(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 類(lèi)存儲(chǔ)到隊(duì)列服務(wù)(可以是 Redis、AWS SQS 或類(lèi)似的服務(wù))中時(shí),對(duì)象被序列化。當(dāng)你在 Laravel 中創(chuàng)建一個(gè)新的 Job 類(lèi)時(shí),它附帶了 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è)類(lèi)包含對(duì) Eloquent 模型的引用,這個(gè)特性允許你自定義序列化過(guò)程。它包含上面看到的鉤子的實(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)識(shí)符將被序列化到隊(duì)列中。當(dāng)實(shí)際處理作業(yè)時(shí),隊(duì)列系統(tǒng)將自動(dòng)從數(shù)據(jù)庫(kù)中重新檢索完整的模型實(shí)例及其加載的關(guān)系。這種模型序列化方法允許將更小的作業(yè)有效負(fù)載發(fā)送到您的隊(duì)列驅(qū)動(dòng)程序。
5. 最后
serialize()
并且unserialize()
是 PHP 的默認(rèn)序列化技術(shù)。事實(shí)上,其他編程語(yǔ)言中有許多庫(kù)允許你根據(jù) PHP 標(biāo)準(zhǔn)序列化對(duì)象和數(shù)據(jù)結(jié)構(gòu),例如 Java 中的這個(gè)庫(kù):
除了這種特定格式,您還可以使用 JSON 標(biāo)準(zhǔn)將數(shù)據(jù)傳輸?shù)酵獠糠?wù)。PHP 通過(guò)兩個(gè)函數(shù)支持這種序列化:json_encode
和json_decode
。
到此這篇關(guān)于一文帶你吃透什么是PHP中的序列化的文章就介紹到這了,更多相關(guān)PHP序列化內(nèi)容請(qǐng)搜索以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持!
