刚刚入职新公司,使用的框架还是很老的symfony 1.4版本,这就很杯具了,只能慢慢学起来。官网只有高版本3.4和4.0的,好不容易找到1.4低版本的还都是英文版,算了就勉为其难的看看吧。先把链接地址发上,说不定有小伙伴也需要,之后便开始学吧。http://www.symfony-project.org/api/1_4/index.html
链接中第一个课程是Api,下面又细分了多个实用类:
action
|
.sfAction 注解为 执行当前请求的所有逻辑. 点进去之后发现其继承了sf组件,并且是下一个sfactions的父类。 sfActions < sfAction < sfComponent
下面来看看有哪些实用的方法:
-
- sfView::NONE renderComponent($moduleName, $componentName, $vars)
Appends the result of the given component execution to the response content.
- sfView::NONE renderComponent($moduleName, $componentName, $vars)
-
- sfView::NONE renderPartial($templateName, $vars)
Appends the result of the given partial execution to the response content.
- sfView::NONE renderPartial($templateName, $vars)
-
- sfView::NONE renderText($text)
Appends the given text to the response content and bypasses the built-in view system.
- sfView::NONE renderText($text)
-
- redirect($url, $statusCode)
Redirects current request to a new URL.
- redirect($url, $statusCode)
-
- mixed getCredential()
Gets credentials the user must have to access this action.
- mixed getCredential()
-
- string getComponent($moduleName, $componentName, $vars)
Returns the component rendered content.
- string getComponent($moduleName, $componentName, $vars)
-
- string getPartial($templateName, $vars)
Returns the partial rendered content.
- string getPartial($templateName, $vars)
-
- sfRoute getRoute()
Returns the current route for this request
- sfRoute getRoute()
-
- string getTemplate()
Gets the name of the alternate template for this sfAction.
- string getTemplate()
-
- postExecute()
Execute an application defined process immediately after execution of this sfAction object.
- postExecute()
-
- preExecute()
Executes an application defined process prior to execution of this sfAction object.
- preExecute()
-
- forward404($message)
Forwards current action to the default 404 error action.
- forward404($message)
-
- forward($module, $action)
Forwards current action to a new one (without browser redirection).
- forward($module, $action)
string getComponent($moduleName, $componentName, $vars)
Returns the component rendered content.
再去看sfActions,本身只有一个方法,其他方法都继承父类和`爷爷辈的`
string execute($request)
Dispatches to the action defined by the 'action' parameter of the sfRequest object.
那么爷爷辈sfcomponent有哪些方法呢?
mixed &($key)
Gets a variable for the template.
mixed execute($request)
Execute any application/business logic for this component.
string generateUrl(, , )
Generates a URL for the given route and arguments.
-
- string getActionName()
Gets the action name associated with this component.
-
- sfContext getContext()
Retrieves the current application context.
- sfContext getContext()
-
- sfController getController()
Retrieves the current sfController object.
- sfController getController()
-
-
- string getModuleName()
Gets the module name associated with this component.
- string getModuleName()
-
-
- sfRequest getRequest()
Retrieves the current sfRequest object.
- sfRequest getRequest()
-
-
- string getRequestParameter($name, $default)
Returns the value of a request parameter.
- string getRequestParameter($name, $default)
-
-
- sfResponse getResponse()
Retrieves the current sfResponse object.
- sfResponse getResponse()
-
- sfUser getUser()
Retrieves the current sfUser object. //获取session对象,sfContext::getInstance->getUser();
- sfUser getUser()
- mixed getVar($name)
Gets a variable set for the template.
-
- string getActionName()
ORM模型:
配置config.yml
alterable config options
type
: The column type (boolean
,tinyint
,smallint
,integer
,bigint
,double
,float
,real
,decimal
,char
,varchar(size)
,longvarchar
,date
,time
,timestamp
,blob
, andclob
)
required
: Set it totrue
if you want the column to be requiredindex
: Set it totrue
if you want to create an index for the column or tounique
if you want a unique index to be created on the column.primaryKey
: Define a column as the primary key for the table.foreignTable
,foreignReference
: Define a column to be a foreign key to another table.
执行 php symfony propel:build --sql 会根据yml的生成对应的sql建表语句到目录 data/sql/下
真实执行建表 则执行php symfony propel:insert-sql
$ php symfony propel:build --model generates PHP files in the lib/model/
directory that can be used to interact with the database.
generates four classes per table: An object of this class represents a single record of the jobeet_job
table
then you could use it like this:
$job = new JobeetJob();
$job->setPosition('Web developer'); $job->save(); echo $job->getPosition(); $job->delete();
INIT DATA into table
create YAML files in the data/fixtures/
directory and use the propel:data-load
task to load them into the database.
LAYOUT:
it use decorator design pattern
$sfuser->setFlash()
$sfuser->getFlash()
url_for('controller/action');
eg:
'job/show?id='.$job->getId()
url_for()
helper converts this internal URI to a proper URL:
/job/show/id/1
include_stylesheets()
Configuration Principles in symfony
For many symfony configuration files, the same setting can be defined at different levels:
- The default configuration is located in the framework
- The global configuration for the project (in
config/
) - The local configuration for an application (in
apps/APP/config/
) - The local configuration restricted to a module (in
apps/APP/modules/MODULE/config/
) 除了在这边配置 引用的css,js 还可以在templates中直接用<?php use_stylesheet('main.css') ?>
<?php user_helper('Text') ?>// apps/frontend/templates/layout.php <title><?php include_slot('title') ?></title>
// apps/frontend/modules/job/templates/showSuccess.php<?php slot( 'title', sprintf('%s is looking for a %s', $job->getCompany(), $job->getPosition())) ?>
PDO:
$ php symfony configure:database "mysql:host=localhost;dbname=jobeet" root mYsEcret
[need three arguments]: [ the PDO DSN, the username, and the password]
Project category:
apps/
frontend/
modules/
job/
actions/
actions.class.php
templates/
indexSuccess.php
首页方法:
public function executeIndex(sfWebRequest $request)
{
/** 设置变量的2种方式 ** / $this->foo = 'bar'; $this->bar = array('bar', 'baz');
$this->setVar('foo','bar'); }
The Request and the Response
The Request
The sfWebRequest
class wraps the $_SERVER
, $_COOKIE
, $_GET
, $_POST
, and $_FILES
PHP global arrays:
Method name | PHP equivalent |
---|---|
getMethod() | $_SERVER['REQUEST_METHOD'] |
getUri() | $_SERVER['REQUEST_URI'] |
getReferer() | $_SERVER['HTTP_REFERER'] |
getHost() | $_SERVER['HTTP_HOST'] |
getLanguages() | $_SERVER['HTTP_ACCEPT_LANGUAGE'] |
getCharsets() | $_SERVER['HTTP_ACCEPT_CHARSET'] |
isXmlHttpRequest() | $_SERVER['X_REQUESTED_WITH'] == 'XMLHttpRequest' |
getHttpHeader() | $_SERVER |
getCookie() | $_COOKIE |
isSecure() | $_SERVER['HTTPS'] |
getFiles() | $_FILES |
getGetParameter() | $_GET |
getPostParameter() | $_POST |
getUrlParameter() | $_SERVER['PATH_INFO'] |
getRemoteAddress() | $_SERVER['REMOTE_ADDR'] |
The Response
The sfWebResponse
class wraps the header()
and setrawcookie()
PHP methods:
Method name | PHP equivalent |
---|---|
setCookie() | setrawcookie() |
setStatusCode() | header() |
setHttpHeader() | header() |
setContentType() | header() |
addVaryHttpHeader() | header() |
addCacheControlHttpHeader() | header() |
URLs
'job/show?id='.$job->getId()
The url_for()
helper converts this internal URI to a proper URL: change to this format => MODULE/ACTION?key=value&key_1=value_1&...
/job/show/id/1
Routing Configuration
# apps/frontend/config/routing.yml homepage: url: / param: { module: default, action: index } default_index: url: /:module param: { action: index } default: url: /:module/:action/*
从上到下依次匹配,第一个满足条件就结束。
/job 匹配到了 default_index
/job/show/id/1 匹配到default
url_for('job/show?id='.$job->getId()) is equivalent to url_for('@default?module=job&action=show&id='.$job->getId())
but letter is faster because it has recognized routing ,parse the route parameters.
you can also directly use explicit route like below
# apps/frontend/config/routing.yml
homepage:
url: /
param: { module: job, action: index }
<!-- apps/frontend/templates/layout.php -->
<h1>
<a href="<?php echo url_for('homepage') ?>"> => job/index
<img src="/legacy/images/logo.jpg" alt="Jobeet Job Board" />
</a>
</h1>
anohter format will parse many parameter: 所以传参时也需要给多个参数,不然匹配不上,同时可以指定部分参数的格式
job_show_user: url: /job/:company/:location/:id/:position
class:sfRequestRoute //指定路由类
param: { module: job, action: show }
requirements: id: \d+
sf_method: [get] //限制请求方式
Object Route Class
Route Class
routing.yml
is internally converted to an object of class sfRoute
link_to()
helper which generates an <a>
tag:
<a href="/job/sensio-labs/paris-france/1/web-developer">Web Developer</a>
<?php echo link_to('Web Developer','/job/sensio-labs/paris-france/1/web-developer',[id=>1]) ?>
redirect => 浏览器跳转url变更 forward =>页面跳转url不变化
SfView
默认视图调用 sfView::SUCCESS
# 将调用indexSuccess.php模板
public
function
executeIndex()
{
return
sfView::SUCCESS;
}
# 将调用listSuccess.php模板
public
function
executeList()
{
}
# symfony将查找actionNameError.php模板
return
sfView::ERROR;
# symfony将查找actionNameMyResult.php模板
return
'MyResult'
; or $this
->setTemplate(
'myCustomTemplate'
);
return
sfView::NONE;
发送空的响应但包含定义的头信息(特别是X-JSON头),定义头通过sfResponse对象,并且放回sfView::HEADER_ONLY常量:
public
function
executeRefresh()
{
$output
=
'<"title","My basic letter"],["name","Mr Brown">'
;
$this
->getResponse()->setHttpHeader(
"X-JSON"
,
'('
.
$output
.
')'
);
return
sfView::HEADER_ONLY;
}
$this
->forward(
'Module'
,
'Action'
);内部跳转,url链接不变化
$this->redirect(''); 外部跳转,url也变化
class
mymoduleActions
extends
sfActions
{
public
function
preExecute()
{
// 这里的代码在所有动作调用之前执行
...
}
public
function
executeIndex()
{
...
}
public
function
executeList()
{
...
$this
->myCustomMethod();
// 调用自定义的方法
}
public
function
postExecute()
{
// 这里的代码会在每个动作结束后执行
...
}
protected
function
myCustomMethod()
{
// 添加自己的方法,虽然他们没有以execute开头
// 在这里,最好将方法定义为protected(保护的)或者private(私有的)
...
}
class
mymoduleActions
extends
sfActions
{
public
function
executeUpload()
{
if
(
$this
->getRequest()->hasFiles())
{
foreach
(
$this
->getRequest()->getFileNames()
as
$fileName
)
{
$fileSize
=
$this
->getRequest()->getFileSize(
$fileName
);
$fileType
=
$this
->getRequest()->getFileType(
$fileName
);
$fileError
=
$this
->getRequest()->hasFileError(
$fileName
);
$uploadDir
= sfConfig::get(
'sf_upload_dir'
);
$this
->getRequest()->moveFile(
'file'
,
$uploadDir
.
'/'
.
$fileName
);
}
}
}
}
}
class
mymoduleActions
extends
sfActions
{
public
function
executeRemoveNickname()
{
$this
->getUser()->getAttributeHolder()->remove(
'nickname'
); //session 属性仓库清除data
}
public
function
executeCleanup()
{
$this
->getUser()->getAttributeHolder()->clear();
}
}
Hello, <?php echo $sf_user->getAttribute('nickname') ?>
Flash属性是一种短命属性,他会在最近的一次请求后消失,这样可以保持你的Session清洁
$this
->setFlash(
'attrib'
,
$value
);
$value
=
$this
->getFlash(
'attrib'
);
<?php
if
(
$sf_flash
->has(
'attrib'
)): ?>
<?php
echo
$sf_flash
->get(
'attrib'
) ?>
<?php
endif
; ?>