search
HomeBackend DevelopmentPHP Tutorial如何让thinkphp在模型中自动完成session赋值小教程_PHP

ThinkPHP

相信用过thinkphp的用户都知道thinkphp的模型可以完成很多辅助功能,比如自动验证、自动完成等,今天在开发中遇到自动完成中需要获取session值

然后自动赋值的功能,具体看代码;

class ArticlelModel extends Model {
  
  protected $_auto = array ( 
    array('addtime','time',1,'function'),
    array('username','getName',1,'callback')
  );
  
  //这个函数获取session里的name值
  protected function getName(){
    return $_SESSION["name"];
  }
}


这里需要注意最后一个参数function和callback的区别;
function:使用函数,会自动去Common/common.php去寻找对应的函数;
callback:使用在当前模型中定义的回调方法

Session 用于Session 设置、获取、删除和管理操作
用法 session($name, $value='')
参数 name(必须):如果传入数组 则表示进行session初始化,如果传入null表示清空当前session,如果是字符串则表示session赋值、获取或者操作。
Value(可选):要设置的session值,如果传入null表示删除session,默认为空字符串
返回值 见详(根据具体的用法返回不同的值)

session函数是一个多元化操作函数,传入不同的参数调用可以完成不同的功能操作,包括下面一些功能。[-more-]
session初始化设置
如果session方法的name参数传入数组则表示进行session初始化设置,例如:
session(array('name'=>'session_id','expire'=>3600));

支持传入的session参数包括:


参数名 说明
id session_id值
name session_name 值
path session_save_path 值
prefix session 本地化空间前缀
expire session.gc_maxlifetime 设置值
domain session.cookie_domain 设置值
use_cookies session.use_cookies 设置值
use_trans_sid session.use_trans_sid 设置值
cache_limiter session_cache_limiter设置值
cache_expire session_cache_expire设置值
type session hander类型,可以使用hander驱动扩展

Session初始化设置方法 无需手动调用,在App类的初始化工作结束后会自动调用,通常项目只需要配置SESSION_OPTIONS参数即可,SESSION_OPTIONS参数的设置是一个数组,支持的索引名和前面的session初始化参数相同。

默认情况下,初始化之后系统会自动启动session,如果不希望系统自动启动session的话,可以设置SESSION_AUTO_START为false,例如:

'SESSION_AUTO_START' =>false

关闭自动启动后可以项目的公共文件或者在控制器中通过手动调用session_start或者session('[start]') 启动session。
session赋值
Session赋值比较简单,直接使用:

session('name','value'); //设置session

相当于:

$_SESSION['name'] = 'value';

session取值

Session取值使用:
$value = session('name');

相当于使用:
$value = $_SESSION['name'];

session删除

session('name',null); // 删除name

相当于:
unset($_SESSION['name']);

要删除所有的session,可以使用:
session(null); // 清空当前的session

相当于:
$_SESSION = array();

session判断
要判断一个session值是否已经设置,可以使用
session('?name');

用于判断名称为name的session值是否已经设置
相当于:
isset($_SESSION['name']);

session管理
session方法支持一些简单的session管理操作,用法如下:
session('[操作名]');

支持的操作名包括:

操作名 含义
start 启动session
pause 暂停session写入
destroy 销毁session
regenerate 重新生成session id

使用示例如下:
session('[pause]'); // 暂停session写入
session('[start]'); // 启动session
session('[destroy]'); // 销毁session
session('[regenerate]'); // 重新生成session id

本地化支持

如果在初始化session设置的时候传入prefix参数或者单独设置了SESSION_PREFIX参数的话,就可以启用本地化session管理支持。启动本地化session后,所有的赋值、取值、删除以及判断操作都会自动支持本地化session。

本地化session支持开启后,生成的session数据格式由原来的
$_SESSION['name'] 变成 $_SESSION['前缀']['name']

假设前缀设置为think,则赋值操作:
session('name','value');  //设置session

相当于:
$_SESSION['think']['name'] = 'value';

取值操作:
$value = session('name');

相当于使用:
$value = $_SESSION['think']['name'];

删除操作:
session('name',null);

相当于:
unset($_SESSION['think']['name']);

清空操作:
session(null);

相当于:
unset($_SESSION['think']);

判断操作:
session('?name');

相当于:
isset($_SESSION['think']['name']);

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.