PHPackages                             bor-attila/cakephp-ptj - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. bor-attila/cakephp-ptj

ActiveCakephp-plugin[Utility &amp; Helpers](/categories/utility)

bor-attila/cakephp-ptj
======================

Plugin for CakePHP which helps to pass PHP variables to Javascript

v1.2.2(3mo ago)23.6kMITPHPPHP &gt;=8.2

Since Sep 28Pushed 3mo ago1 watchersCompare

[ Source](https://github.com/bor-attila/cakephp-ptj)[ Packagist](https://packagist.org/packages/bor-attila/cakephp-ptj)[ Docs](https://github.com/bor-attila/cakephp-ptj/)[ RSS](/packages/bor-attila-cakephp-ptj/feed)WikiDiscussions master Synced 2d ago

READMEChangelog (6)Dependencies (2)Versions (8)Used By (0)

CakePHP - Php to Javascript
===========================

[](#cakephp---php-to-javascript)

Easily pass PHP variables to Javascript

This Plugin requires: **CakePHP &gt;=4.x**

Installation
------------

[](#installation)

You can install this plugin into your CakePHP application using [composer](https://getcomposer.org).

The recommended way to install composer packages is:

```
composer require bor-attila/cakephp-ptj

```

Enable the plugin in your **Application.php**:

```
$this->addPlugin('PhpToJavascript');

```

In **View\\AppView.php** add this to the **initialize** method:

```
$this->loadHelper('PhpToJavascript.PhpToJavascript');

```

TL;DR
-----

[](#tldr)

Instead of

```
echo $this->Html->scriptBlock('var user = ' . json_encode(['firtname' => 'John', 'lastname' => 'Connor', 'age' => 15]));

```

just use (in layout)

```

        ...

```

In the client side you can use:

```
p('user'); // Object { firtname: "John", lastname: "Connor", age: 15 }

```

When and why ?
--------------

[](#when-and-why-)

When you build a hybrid CakePHP and Javascript application, sometimes you want to pass some variable to client. Sure, you can build an API for this - but since the request has already "reached the controller" (to get the template) you can simply "echoes" the variables and if you want to have a nice way to do this - you can use this plugin.

I think this is a better way than building an API, for example, just to know: user's IP address, the current user id, the current language, etc ...

Configuration
-------------

[](#configuration)

The default configuration is:

```
'function' => 'p',
'storage' => '__phptojavascript',
'encode' => [
    'options' => 0,
    'depth' => 512,
],
'cache' => [
    'enabled' => true,
    'key' => '__phptojavascript',
    'config' => 'default',
]

```

- `function` the name of the function which helps to reach your stored variable.
- `storage` the name of the global javascript variable where your php variables are stored. Just make sure this is an unique variable name.
- `encode` parameters of the **json\_encode** function
- `cache` the global function always generated by based on `function` and `storage` configuration. You can use this parameter to store it.

Usage (PHP)
-----------

[](#usage-php)

```
//add multiple variable at once
$this->PhpToJavascript->add([
    'user' => $user,
    'language' => $lang
]);

//adding simple number if does not exists `var1`
$this->PhpToJavascript->add('var1', 1);

//adding array if does not exists `user`, note that you don't need to call json_encode. The plugin will do it for you
$this->PhpToJavascript->add('user', ['firtname' => 'John', 'lastname' => 'Connor', 'age' => 15]);

//setting and array if exists, will be overwritten
$this->PhpToJavascript->set('user', ['firtname' => 'John', 'lastname' => 'Connor', 'age' => 15]);

//or remove before $this->PhpToJavascript->get() is called
$this->PhpToJavascript->remove('user');

//prints the main javascript file containing the window.__phptojavascript variable and the p function
echo $this->PhpToJavascript->get();

```

Usage (Javascript)
------------------

[](#usage-javascript)

```
//the default p function
p(string key, function mutator, default);

p('not_exists'); // undefined

p('user', null, false); // { .... }

p('not_exists', null, false); // false

p('user'); // Object { firtname: "John", lastname: "Connor", age: 15 }
p('user', user => user.age); // 15

// from version 1.1, the second parameter can be a default value or a mutator
// p(string key, any default);

// if the requested key WAS NOT found
//
// 1. then the second parameter is returned if there is only 2 parameter given
console.assert(p('not_exists', false) === false);
// 2. then the second parameter is ignored, and the third parameter is returned if there is 3 parameter or more
console.assert(p('not_exists', 'ignored', false) === false);
// 3. then the default result is undefined
console.assert(typeof p('not_exists') === 'undefined');

// if the requested key WAS found
//
// 1. then the value stored on the PHP side will be returned
console.assert(p('user') === window.__phptojavascript.user);
// 2. and the second parameter is a function, then the result will be 'mutated' by the function
console.assert(p('user', x => x.age) === 15);
// 3. and the second parameter is not a function, then the value stored on the PHP side will be returned and the other
// parameters are ignored
console.assert(p('user', 'not a function, so this is ignored', 'default value, but ignored') === window.__phptojavascript.user);

```

Bundle the main function or extending
-------------------------------------

[](#bundle-the-main-function-or-extending)

You can use the **generate\_php\_js** command to generate a static file with the `p` function. The command to generates a static js file with the `window.__phptojavascript = {}; p = ...` initialization. You can extend it or bundle it - your choose, but don't forget to tell this to the **get** method.

```
bin/cake generate_php_js

```

```
echo $this->PhpToJavascript->get(false);

```

This prevents generating and including the main function into the js output.

Todo
----

[](#todo)

Tests.

###  Health Score

48

—

FairBetter than 94% of packages

Maintenance80

Actively maintained with recent releases

Popularity19

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity71

Established project with proven stability

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~324 days

Recently: every ~471 days

Total

7

Last Release

107d ago

PHP version history (3 changes)v1.0.0PHP &gt;=7.2

1.2PHP &gt;=8.1

v1.2.1PHP &gt;=8.2

### Community

Maintainers

![](https://www.gravatar.com/avatar/df1db3baad4521e8d0ea78475db6c6a3a4d9b9dd1278260280445123505da36f?d=identicon)[bor-attila](/maintainers/bor-attila)

---

Top Contributors

[![bor-attila](https://avatars.githubusercontent.com/u/6832955?v=4)](https://github.com/bor-attila "bor-attila (12 commits)")

---

Tags

phpjavascriptcakephpsharevariablepass

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/bor-attila-cakephp-ptj/health.svg)

```
[![Health](https://phpackages.com/badges/bor-attila-cakephp-ptj/health.svg)](https://phpackages.com/packages/bor-attila-cakephp-ptj)
```

###  Alternatives

[dereuromark/cakephp-tools

A CakePHP plugin containing lots of useful and reusable tools

338920.1k32](/packages/dereuromark-cakephp-tools)[hisune/echarts-php

A php wrapper for echarts javascript libraries

327201.9k5](/packages/hisune-echarts-php)[ishanvyas22/asset-mix

Asset Mix plugin for CakePHP

3375.4k2](/packages/ishanvyas22-asset-mix)[trentrichardson/cakephp-shrink

Compiles, combines, and minifies javascript, coffee, less, scss, and css

1619.3k](/packages/trentrichardson-cakephp-shrink)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
