Remove more deprecated APIs

This commit is contained in:
Aaron Carlino 2017-08-07 11:46:19 +12:00
parent e4fba5a7b1
commit 6c0629f025
12 changed files with 77 additions and 306 deletions

View File

@ -279,7 +279,7 @@ class HomePageController extends PageController
$submission = new BrowserPollSubmission();
$form->saveInto($submission);
$submission->write();
Session::set('BrowserPollVoted', true);
$this->getRequest()->getSession()->set('BrowserPollVoted', true);
return $this->redirectBack();
}
}
@ -297,7 +297,7 @@ class HomePageController extends PageController
// ...
public function BrowserPollForm()
{
if (SilverStripe\Control\Session::get('BrowserPollVoted')) {
if ($this->getRequest()->getSession()->get('BrowserPollVoted')) {
return false;
}
// ...

View File

@ -90,7 +90,7 @@ This class implements the *Iterator*-interface, and provides convenience-methods
### DELETE
Deletion can be done either by calling `DB::query`/`DB::prepared_query` directly,
by creating a `SQLDelete` object, or by transforming a `SQLQuery` into a `SQLDelete`
by creating a `SQLDelete` object, or by transforming a `SQLSelect` into a `SQLDelete`
object instead.
For example, creating a `SQLDelete` object
@ -104,11 +104,11 @@ For example, creating a `SQLDelete` object
```
Alternatively, turning an existing `SQLQuery` into a delete
Alternatively, turning an existing `SQLSelect` into a delete
```php
$query = SQLQuery::create()
$query = SQLSelect::create()
->setFrom('"SiteTree"')
->setWhere(['"SiteTree"."ShowInMenus"' => 0])
->toDelete();

View File

@ -22,7 +22,7 @@ instance with a template name or an array of templates to render.
**mysite/code/Page.php**
```php
$arrayData = new SilverStripe/View/ArrayData([
$arrayData = new SilverStripe\View\ArrayData([
'Name' => 'John',
'Role' => 'Head Coach'
]);

View File

@ -50,7 +50,7 @@ user does not influence your template content, you can update this key as below;
```yaml
SSViewer:
SilverStripe\View\SSViewer:
global_key: '$CurrentReadingMode, $Locale'
```
@ -296,20 +296,3 @@ Or:
<% end_cached %>
<% end_loop %>
```
## Cache expiry
The default expiry for partial caches is 10 minutes. The advantage of a short cache expiry is that if you have a problem
with your caching logic, the window in which stale content may be shown is short. The disadvantage, particularly for
low-traffic sites, is that cache blocks may expire before they can be utilised. If you're confident that you're caching
logic is sound, you could increase the expiry dramatically.
**mysite/_config.php**
```php
// Set partial cache expiry to 7 days
SS_Cache::set_cache_lifetime('cacheblock', 60 * 60 * 24 * 7);
```

View File

@ -149,7 +149,7 @@ old cache keys will be garbage collected as the cache fills up.
$cache = Injector::inst()->get(CacheInterface::class . '.myCache');
// Automatically changes when any group is edited
$cacheKey = implode(['groupNames', $member->ID, Groups::get()->max('LastEdited')]);
$cacheKey = implode(['groupNames', $member->ID, Group::get()->max('LastEdited')]);
$cache->set($cacheKey, $member->Groups()->column('Title'));
```

View File

@ -61,16 +61,15 @@ You can define subclasses of [Member](api:SilverStripe\Security\Member) to add e
```
To ensure that all new members are created using this class, put a call to [Object::useCustomClass()](api:Object::useCustomClass()) in
(project)/_config.php:
To ensure that all new members are created using this class, put it in `Injector`.
```php
Object::useCustomClass("Member", "MyMember");
```yaml
SilverStripe\Core\Injector\Injector:
SilverStripe\Security\Member:
class: My\Project\MyMember
```
Note that if you want to look this class-name up, you can call Object::getCustomClass("Member")
## Overloading getCMSFields()
If you overload the built-in public function getCMSFields(), then you can change the form that is used to view & edit member

View File

@ -348,6 +348,8 @@ PHP:
```php
use SilverStripe\Core\Convert;
use SilverStripe\Control\Controller;
use SilverStripe\ORM\FieldType\DBText;
use SilverStripe\ORM\FieldType\DBHTMLText;
class MyController extends Controller
{
@ -356,8 +358,8 @@ PHP:
{
$htmlTitle = '<p>Your results for:' . Convert::raw2xml($request->getVar('Query')) . '</p>';
return $this->customise([
'Query' => Text::create($request->getVar('Query')),
'HTMLTitle' => HTMLText::create($htmlTitle)
'Query' => DBText::create($request->getVar('Query')),
'HTMLTitle' => DBHTMLText::create($htmlTitle)
]);
}
}
@ -385,6 +387,7 @@ PHP:
```php
use SilverStripe\Control\Controller;
use SilverStripe\ORM\FieldType\DBText;
class MyController extends Controller
{
@ -394,7 +397,7 @@ PHP:
$rssRelativeLink = "/rss?Query=" . urlencode($_REQUEST['query']) . "&sortOrder=asc";
$rssLink = Controller::join_links($this->Link(), $rssRelativeLink);
return $this->customise([
"RSSLink" => Text::create($rssLink),
"RSSLink" => DBText::create($rssLink),
]);
}
}
@ -724,6 +727,7 @@ For sensitive pages, such as members areas, or places where sensitive informatio
and `Date: <current date>` will ensure that sensitive content is not stored locally or able to be retrieved by
unauthorised local persons. SilverStripe adds the current date for every request, and we can add the other cache
headers to the request for our secure controllers:
```php
use SilverStripe\Control\HTTP;
use SilverStripe\Control\Controller;

View File

@ -1,249 +0,0 @@
summary: Consume external data through their RESTFul interfaces.
# Restful Service
[RestfulService](api:RestfulService) is used to enable connections to remote web services through PHP's `curl` command. It provides an
interface and utility functions for generating a valid request and parsing the response returned from the web service.
<div class="alert" markdown="1">
RestfulService currently only supports XML. It has no JSON support at this stage.
</div>
## Examples
### Creating a new RestfulObject
`getWellingtonWeather` queries the Yahoo Weather API for an XML file of the latest weather information. We pass a query
string parameter `q` with the search query and then convert the resulting XML data to an `ArrayList` object to display
in the template.
**mysite/code/Page.php**
```php
public function getWellingtonWeather()
{
$fetch = new RestfulService(
'https://query.yahooapis.com/v1/public/yql'
);
$fetch->setQueryString([
'q' => 'select * from weather.forecast where woeid in (select woeid from geo.places(1) where text="Wellington, NZ")'
]);
// perform the query
$conn = $fetch->request();
// parse the XML body
$msgs = $fetch->getValues($conn->getBody(), "results");
// generate an object our templates can read
$output = new ArrayList();
if($msgs) {
foreach($msgs as $msg) {
$output->push(new ArrayData([
'Description' => Convert::xml2raw($msg->channel_item_description)
]));
}
}
return $output;
}
```
## Features
### Basic Authenication
```php
$service = new RestfulService("http://example.harvestapp.com");
$service->basicAuth('username', 'password');
```
### Make multiple requests
```php
$service = new RestfulService("http://example.harvestapp.com");
$peopleXML = $service->request('/people');
$people = $service->getValues($peopleXML, 'user');
// ...
$taskXML = $service->request('/tasks');
$tasks = $service->getValues($taskXML, 'task');
```
### Caching
To set the cache interval you can pass it as the 2nd argument to constructor.
```php
$expiry = 60 * 60; // 1 hour;
$request = new RestfulService("http://example.harvestapp.com", $expiry );
```
### Getting Values & Attributes
You can traverse through document tree to get the values or attribute of a particular node using XPath. Take for example
the following XML that is returned.
```xml
<entries>
<entry id='12'>Sally</entry>
<entry id='15'>Ted</entry>
<entry id='30'>Matt</entry>
<entry id='22'>John</entry>
</entries>
```
To extract the id attributes of the entries use:
```php
$this->getAttributes($xml, "entries", "entry");
// array(array('id' => 12), array('id' => '15'), ..)
```
To extract the values (the names) of the entries use:
```php
$this->getValues($xml, "entries", "entry");
// array('Sally', 'Ted', 'Matt', 'John')
```
### Searching for Values & Attributes
If you don't know the exact position of DOM tree where the node will appear you can use xpath to search for the node.
<div class="note">
This is the recommended method for retrieving values of name spaced nodes.
</div>
```xml
<media:guide>
<media:entry id="2030">video</media:entry>
</media:guide>
```
To get the value of entry node with the namespace media, use:
```php
$this->searchValue($response, "//media:guide/media:entry");
// array('video');
```
## Best Practices
### Handling Errors
If the web service returned an error (for example, API key not available or inadequate parameters),
[RestfulService](api:RestfulService) can delegate the error handling to it's descendant class. To handle the errors, subclass
`RestfulService and define a function called errorCatch.
```php
class MyRestfulService extends RestfulService
{
public function errorCatch($response)
{
$err_msg = $response;
if(strpos($err_msg, '<') === false) {
user_error("YouTube Service Error : $err_msg", E_USER_ERROR);
}
return $response;
}
}
```
If you want to bypass error handling, define `checkErrors` in the constructor for `RestfulService`
```php
class MyRestfulService extends RestfulService
{
public function __construct($expiry = NULL)
{
parent::__construct('http://www.flickr.com/services/rest/', $expiry);
$this->checkErrors = false;
}
}
```
### Setting cURL options
Restful service uses cURL to make requests. There are various settings that can be defined on the cURL
request (see http://www.php.net/manual/en/function.curl-setopt.php) via the curl_setopts function.
There are two ways to define these for `RestfulService`; they can be global settings or per request settings.
It is important to note that your cURL options will be applied LAST and so take preference over any default
values that `RestfulService` sets (such as `CURLOPT_RETURNTRANSFER`) so changing these options may result
in unexpected behaviour or broken functionality.
#### Global cURL settings
To set global cURL settings you can update the `RestfulService` config via the Config system or YAML.
Here is an example to increase the HTTP Timeout globally. Insert this in your `_config.php` file:
```php
SilverStripe\Core\Config\Config::inst()->update('RestfulService', 'default_curl_options', [
CURLOPT_DNS_CACHE_TIMEOUT => 3600,
CURLOPT_CONNECTTIMEOUT => 10,
]);
```
#### Per request settings
When making a request using `RestfulService` one can also pass through an array of cURL options in the last
parameter in `RestfulService::request()`.
For example:
```php
//cURL options
$curlOptions = [
CURLOPT_UNRESTRICTED_AUTH => true,
];
$service = new RestfulService('http://example.com/');
$service->request('service.json', 'GET', null, null, $curlOptions);
```
## How to's
* [Embed an RSS Feed](how_tos/embed_rss)
## API Documentation
* [RestfulService](api:RestfulService)

View File

@ -155,7 +155,7 @@ In order to set the correct layout classes, we also need a custom template.
To obey the inheritance chain, we use `$this->getTemplatesWithSuffix('_EditForm')` for
selecting the most specific template (so `MyAdmin_EditForm.ss`, if it exists).
The form should be of type `CMSForm` rather than `Form`, since it allows the use
The form should use a `LeftAndMainFormRequestHandler`, since it allows the use
of a `PjaxResponseNegotiator` to handle its display.
Basic example form in a CMS controller subclass:
@ -163,18 +163,20 @@ Basic example form in a CMS controller subclass:
```php
use SilverStripe\Forms\TabSet;
use SilverStripe\Forms\FieldList;
use SilverStripe\Forms\Tab;
use SilverStripe\Forms\TextField;
use SilverStripe\Forms\FormAction;
use SilverStripe\Admin\LeftAndMain;
use SilverStripe\Admin\LeftAndMainFormRequestHandler;
class MyAdmin extends LeftAndMain
{
function getEditForm() {
return CMSForm::create(
return Form::create(
$this,
'EditForm',
new FieldSet(
new FieldList(
TabSet::create(
'Root',
Tab::create('Main',
@ -182,10 +184,14 @@ Basic example form in a CMS controller subclass:
)
)->setTemplate('CMSTabset')
),
new FieldSet(
new FieldList(
FormAction::create('doSubmit')
)
)
// Use a custom request handler
->setRequestHandler(
LeftAndMainFormRequestHandler::create($form)
)
// JS and CSS use this identifier
->setHTMLID('Form_EditForm')
// Render correct responses on validation errors

View File

@ -35,8 +35,9 @@ The following example will create a report to list every page on the current sit
###CustomSideReport.php
```php
use Page;
use SilverStripe\Reports\Report;
class CustomSideReport_NameOfReport extends SS_Report
class CustomSideReport_NameOfReport extends Report
{
// the name of the report
@ -68,7 +69,7 @@ More useful reports can be created by changing the `DataList` returned in the `s
## Notes
* `CustomSideReport_ReportName` must extend `SS_Report`
* `CustomSideReport_ReportName` must extend `Report`
* It is recommended to place all custom reports in the 1 file.
* Create a *CustomSideReport.php* file and add classes as you need them inside for each report

View File

@ -21,22 +21,25 @@ This example uses [Cache](api:Cache) in some custom code, and the same cache is
```php
use SilverStripe\ORM\DataObject;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\Core\Flushable;
use Psr\SimpleCache\CacheInterface;
class MyClass extends DataObject implements Flushable
{
public static function flush()
{
Cache::factory('mycache')->clean(Zend_Cache::CLEANING_MODE_ALL);
Injector::inst()->get(CacheInterface::class . '.mycache')->clear();
}
public function MyCachedContent()
{
$cache = Cache::factory('mycache')
$something = $cache->load('mykey');
$cache = Injector::inst()->get(CacheInterface::class . '.mycache')
$something = $cache->get('mykey');
if(!$something) {
$something = 'value to be cached';
$cache->save($something, 'mykey');
$cache->set('mykey', $something);
}
return $something;
}
@ -52,6 +55,7 @@ flush so they are re-created on demand.
```php
use SilverStripe\ORM\DataObject;
use SilverStripe\Core\Flushable;
class MyClass extends DataObject implements Flushable
{

View File

@ -10,11 +10,34 @@ In order to support things like testing, the session is associated with a partic
this is loaded from and saved to the regular PHP session, but for things like static-page-generation and
unit-testing, you can create multiple Controllers, each with their own session.
## Getting the session instance
If you're in a controller, the `Session` object will be bound to the `HTTPRequest` for your controller.
```php
use SilverStripe\Control\Controller;
class MyController extends Controller
{
public function MySession()
{
return $this->getRequest()->getSession();
}
}
```
Otherwise, if you're not in a controller, get the request as a service.
```php
$request = Injector::inst()->get(HTTPRequest::class);
$session = $request->getSession();
```
## set
```php
Session::set('MyValue', 6);
$session->set('MyValue', 6);
```
Saves the value of to session data. You can also save arrays or serialized objects in session (but note there may be
@ -23,11 +46,11 @@ size restrictions as to how much you can save).
```php
// saves an array
Session::set('MyArrayOfValues', ['1','2','3']);
$session->set('MyArrayOfValues', ['1','2','3']);
// saves an object (you'll have to unserialize it back)
$object = new Object();
Session::set('MyObject', serialize($object));
$session->set('MyObject', serialize($object));
```
@ -39,13 +62,13 @@ can use this anywhere in your PHP files.
```php
echo Session::get('MyValue');
echo $session->get('MyValue');
// returns 6
$data = Session::get('MyArrayOfValues');
$data = $session->get('MyArrayOfValues');
// $data = array(1,2,3)
$object = unserialize(Session::get('MyObject', $object));
$object = unserialize($session->get('MyObject', $object));
// $object = Object()
```
@ -54,7 +77,7 @@ can use this anywhere in your PHP files.
You can also get all the values in the session at once. This is useful for debugging.
```php
Session::get_all();
$session->getAll();
// returns an array of all the session values.
```
@ -64,13 +87,13 @@ You can also get all the values in the session at once. This is useful for debug
Once you have accessed a value from the Session it doesn't automatically wipe the value from the Session, you have
to specifically remove it.
```php
Session::clear('MyValue');
$session->clear('MyValue');
```
Or you can clear every single value in the session at once. Note SilverStripe stores some of its own session data
including form and page comment information. None of this is vital but `clear_all` will clear everything.
```php
Session::clear_all();
$session->clearAll();
```
## Secure Session Cookie
@ -80,8 +103,8 @@ In certain circumstances, you may want to use a different `session_name` cookie
```yml
Session:
cookie_secure: true
SilverStripe\Control\Session:
cookie_secure: true
```
This uses the session_name `SECSESSID` for `https` connections instead of the default `PHPSESSID`. Doing so adds an extra layer of security to your session cookie since you no longer share `http` and `https` sessions.