SoapServer::setPersistence

(PHP 5, PHP 7, PHP 8)

SoapServer::setPersistenceУстанавливает режим сохранения SoapServer

Описание

public SoapServer::setPersistence(int $mode): void

Эта функция позволяет изменять режим сохранения объекта SoapServer между запросами. Эта функция позволяет сохранять данные между запросами используя механизм сессий PHP. Этот метод влияет только на SoapServer после экспорта функций, используя SoapServer::setClass().

Замечание:

Сохранение SOAP_PERSISTENCE_SESSION гарантирует сохранение только объектов заданного класса, но не статические данные класса. В этом случае используйте $this->bar вместо self::$bar.

Замечание:

SOAP_PERSISTENCE_SESSION сериализует данные объекта класса и сохраняет их между запросами. Для корректной работы с ресурсами (например, PDO), следует использовать магические методы __wakeup() и __sleep().

Список параметров

mode

Одна из констант SOAP_PERSISTENCE_XXX.

SOAP_PERSISTENCE_REQUEST - данные SoapServer не сохраняются между запросами. Это поведение по умолчанию любого объекта SoapServer после вызова setClass.

SOAP_PERSISTENCE_SESSION - данные SoapServer сохраняются между запросами. Это достигается путём сериализации объекта SoapServer в $_SESSION['_bogus_session_name'], следовательно необходимо вызвать session_start() перед включением этого режима.

Возвращаемые значения

Функция не возвращает значения после выполнения.

Примеры

Пример #1 Пример использования SoapServer::setPersistence()

<?php
class MyFirstPersistentSoapServer {
private
$resource; // (Такие как PDO, mysqli и т.д.)
public $myvar1;
public
$myvar2;

public function
__construct() {
$this->__wakeup(); // Вызываем __wakeup для пересоздания $resource
}

public function
__wakeup() {
$this->resource = CodeToStartOurResourceUp();
}

public function
__sleep() {
// Не сохраняем $resource здесь.
// Ошибка в этом методе приведёт к тому, что при последующей десериализации
// мы не сможем восстановить состояние объекта.
return array('myvar1','myvar2');
}
}

try {
session_start();
$server = new SoapServer(null, array('uri' => $_SERVER['REQUEST_URI']));
$server->setClass('MyFirstPersistentSoapServer');
// setPersistence НЕОБХОДИМО вызвать после setClass, поскольку setClass
// принудительно устанавливает SESSION_PERSISTENCE_REQUEST.
$server->setPersistence(SOAP_PERSISTENCE_SESSION);
$server->handle();
} catch(
SoapFault $e) {
error_log("ОШИБКА SOAP: ". $e->getMessage());
}
?>

Смотрите также

  • SoapServer::setClass() - Устанавливает класс, который обрабатывает SOAP-запросы

add a note add a note

User Contributed Notes 6 notes

up
2
csnaitsirch at web dot de
14 years ago
I want to give one example for the order of commands if you want to use a class in persistence mode.

<?php
// 1. class definition or include
class UserService
{
    public function
__construct() { }
}

// 2. start the session after defining or including the class!!
session_start();

// 3. instanciate the server
$server = new SoapServer(null, array("something"));

// 4. set the class to use
$server->setClass('UserService');

// 5. set persistance mode
$server->setPersistence(SOAP_PERSISTENCE_SESSION);

// 6. handle the request
$server->handle();
?>
up
1
boogiebug at gmail dot com
16 years ago
setPersistence works only for a single instance of service class.

To use multiple instance of services objects, you need to instantiate the classes into objects and use an undocumented SoapServer's method - setObject() to add the service object into the SoapServer object, and handle the service object persistence with $_SESSION instead.

For example:

$ServiceObjects = array()
$ServiceObjects[0] = new ServiceClass1();
$ServiceObjects[1] = new ServiceClass2();
$ServiceObjects[2] = new ServiceClass3();

$_SESSION['ServiceClass1'] = $ServiceObjects[0];
$_SESSION['ServiceClass2'] = $ServiceObjects[1];
$_SESSION['ServiceClass3'] = $ServiceObjects[2];

...

$Servers = array()
for ( $i = 0; $i < count($ServiceObjects); i++)
{
  $s = new SoapServer($wsdl);
  $s->setObject($ServiceObject[$i]);
  $Servers[] = $s;
}

...

$Server[$i]->handle()

...
up
1
jan at pinna dot nl
16 years ago
I found that using both modes (SOAP_PERSISTENCE_SESSION and SOAP_PERSISTENCE_REQUEST) cannot be used simultaniously. Because it didn't work at once, I started experimenting by using different settings and as stated below in the comments, "...also use SOAP_PERSISTENCE_REQUEST to save objects between requests" led me to think it was nessecary to use both modes. Well, it might for others, be but for me it turned out a day of freaking out ;) (trying all kinds of session stuff, etc etc).
Also, if persistence doesn't work, please check if session_start() is called somewhere in the script and try not to call it twice or whatsoever: it won't work...
up
1
jared at ws-db dot com
19 years ago
I had some issues getting session persistence (SOAP_PERSISTENCE_SESSION) to work. I finally got it working after setting session.auto_start=0, and then only calling session_start() in the script containing the SoapServer. Maybe this is obvious, but took me a bit to figure it out.

I only tried it with session.use_cookies=1, so if the settings above don't work for you, make sure cookies are enabled, though it may work without the need for cookies.
up
1
cperez1000 at hotmail dot com
19 years ago
Always remember to place the "setPersistence" method before the handle method, otherwise it won't work.  It sounds obvious, but it's still a very common mistake, since no errors are shown.
up
0
doug dot manley at gmail dot com
16 years ago
When using "SoapServer::setPersistence( SOAP_PERSISTENCE_SESSION )", you apparently MUST include the class that was used in "SoapServer::setClass()" BEFORE any "session_*" commands.

I found this out using "__autoload()" and a whole lot of "syslog()"; it kept failing to include the class that I was using for my soap server, but that class is ONLY ever referenced by the page itself, and even then only for the purposes of setting the class for the soap server; none of my code would ever cause it to autoload.  The problem was that I was including my session-handling code first.

If the session gets started BEFORE the page defines the class definition, then persistence CANNOT happen.

The order should be:
1. Include the class for use with the soap server.
2. Start up your session.
3. Set up your soap server.
4. Handle your soap request.
To Top