in asp.net there are controls like grideview, menus, .....
how to develop a web control in php like an editor [html, jscript, ajax calls to server] it is used repeatedly and the improvement of control will be better if we can separate it?
First of, be aware that in PHP "control" and worse, "controller" means completely differently.
I've not used ASP, but I've used Delphi extensively, as well as Delphi for PHP, which does the same thing you are asking about (yes, in PHP).
Basically, you need some sort of framework to build this stuff on, as Johann said, you might want to use MVC, but you don't really have to.
Example of such a system (without MVC):
class TControl {
public $width=0;
public $height=0;
public $name='ControlN';
public function render(){
echo '<div style="width:'.(int)$this->width.'px; height:'.(int)$this->height.'px;"/>';
}
}
class TLabel {
public $caption='Label';
public function render(){
echo '<div style="width:'.(int)$this->width.'px; height:'.(int)$this->height.'px;">'.htmlspecialchars($this->caption,ENT_QUOTES).'</div>';
}
}
$label=new TLabel();
$label->width=200;
$label->height=24;
$label->caption='My label!';
$label->render();
In PHP you write all 'controllers' in plain HTML.
If you want 'controllers' that you use more often, then make functions for them, f.ex;
function list($array)
{
$output = '';
foreach($array as $item) $output .= "<li>$item</li>";
return "<ul>$output</ul>";
}
Now you got an 'list controller'.
ASP.net tries to mimic Windows Forms, this allows Windows Forms users to quickly get a website up and running. And as it mimics Windows Forms they created several preloaded user controls that you can insert into a web page. All these do is produce the styles, JavaScript and the HTML necessary to show the control on the client browser with your configured options. You could try to produce a similar effect in PHP , with .php that you include. For example creating a button.php and then including it where you want the button to be displayed.
But for simplicity I find that the MVC approach to development with PHP and a Framework is much more cleaner.
Related
I want to be able to call the CakeS3 plugin from the Cake Shell. However, as I understand it components cannot be loaded from the shell. I have read this post outlining strategies for overcoming it: using components in Cakephp 2+ Shell - however, I have had no success. The CakeS3 code here is similar to perfectly functioning cake S3 code in the rest of my app.
<?php
App::uses('Folder','Utility');
App::uses('File','Utility');
App::uses('CakeS3.CakeS3','Controller/Component');
class S3Shell extends AppShell {
public $uses = array('Upload', 'User', 'Comment');
public function main() {
$this->CakeS3 = new CakeS3.CakeS3(
array(
's3Key' => 'key',
's3Secret' => 'key',
'bucket' => 'bucket')
);
$this->out('Hello world.');
$this->CakeS3->permission('private');
$response = $this->CakeS3->putObject(WWW_ROOT . '/file.type' , 'file.type', $this->CakeS3->permission('private'));
if ($response == false){
echo "it failed";
} else {
echo "it worked";
}
}
This returns an error of "Fatal error: Class 'CakeS3' not found in /home/app/Console/Command/S3Shell.php. The main reason I am trying to get this to work is so I can automate some uploads with a cron. Of course, if there is a better way, I am all ears.
Forgive me this "advertising"... ;) but my plugin is probably better written and has a better architecture than this CakeS3 plugin if it is using a component which should be a model or behaviour task. Also it was made for exactly the use case you have. Plus it supports a few more storage systems than only S3.
You could do that for example in your shell:
StorageManager::adapter('S3')->write($key, StorageManager::adapter('Local')->read($key));
A file should be handled as an entity on its own that is associated to whatever it needs to be associated to. Every uploaded file (if you use or extend the models that come with the plugin, if not you have to take care of that) is stored as a single database entry that contains the name of the config that was used and some meta data for that file. If you do the line of code above in your shell you will have to keep record in the table if you want to access it this way later. Just check the examples in the readme.md out. You don't have to use the database table as a reference to your files but I really recommend the system the plugin implements.
Also, you might not be aware that WWW_ROOT is public accessible, so in the case you store sensitive data there it can be accessed publicly.
And finally in a shell you should not use echo but $this->out() for proper shell output.
I think the App:uses should look like:
App::uses('CakeS3', 'CakeS3.Controller/Component');
I'm the author of CakeS3, and no I'm afraid there is no "supported" way to do this as when we built this plugin, we didn't need to run uploads from shell and just needed a simple interface to S3 from our controllers. We then open sourced the plugin as a simple S3 connector.
If you'd like to have a go at modifying it to support shell access, I'd welcome a PR.
I don't have a particular road map for the plugin, so I've tagged your issue on github as an enhancement and will certainly consider it in future development, but I can't guarantee that it would fit your time requirements so that's why I mention you doing a PR.
I have a simple controller file StudentController.php
<?php
$data = array();
$data["firstName"] = $_GET["firstName"];
loadView("StudentView.php", $data);
?>
I have a even simpler view file called StudentView.php
<?php
echo $firstName;
?>
I have absolutely no idea how to implement loadView($view, $data) function. I want variables from $data in controller became available in view ($data["foo"] from controller became $foo in view)
I want achieve what is very easy to do in CodeIgniter but I have no idea how it is implemented. I tried to look into Controller.php and Loader.php in source files, but it was too messy for me to understand.
I don't want to use CodeIgniter or any other framework, I want to natively do in PHP.
If you're going to be building a large website to be used by the general public, a framework is generally a good idea for multiple reasons:
Properly unit tested - generally speaking, you can be confident that the core of your website is functioning as it's intended to
Community support - have questions and you can easily get answers; generally these frameworks are open sourced and usually actively developed by the PHP community
Secure - Framework developers are, well, framework developers; and they have been trained to write code with security as a top priority
However, this question has nothing to do with frameworks vs not, so I'll answer the question you asked with a very simple function:
function loadView($view, $data) {
extract($data);
ob_start();
require_once $view;
$contents = ob_get_contents();
ob_end_clean();
return $contents;
}
You can chose to return the contents or print them directly, but that function should do what you need. I'm making no guarantees about the security of this code, and I have obviously done no error checking. But it should serve as a great foundation to get you started.
I'm completely new to jQuery and Ajax, but I've managed to learn how to do the Hello World, populate a select tag, etc, etc...
Problem is, I don't like to use structural PHP. The way I learned I have to call some PHP file with $.getJSON and that file has to "echo" my result.
What I want is to be able to call a PHP file that is actually a class with some methods and the return of the method would be what JavaScript would receive instead of just an echo result.
Thanks for your attention.
Ps.: I have a lot of experience with PHP-OOP and Flex+PHP using Amfphp. I'm trying to build a different version of view and I would like to re-use the classes that Flex already use.
jQuery runs on your computer, and PHP runs on the server. PHP and jQuery can only communicate via a series of well-crafted strings. On the server, you are free to create objects, run methods, manipulate output, and anything else. However, if you're going to be feeding that data back into your jQuery application (still running on the client's machine), you'll need to echo (or output) the results of your PHP script.
You may consider something like this:
$.post('server.php', { 'class':'foo', 'method':'bar' }, function( response ) {
/* do something with the output of $foo->bar(); */
});
As you can see here, I can define the class and method I'd like to have called on the server. From server.php, we would look to $_POST['class'] and $_POST['method'] to determine what we will instantiate, and which methods we will run.
The AMF is somehow different from HTTP, they're different protocols.
When using AJAX (jQuery or not), you're calling HTTP methods on URIs, not OOP methods. So everything ends up in a minimum of two mappings:
Your application logic mapped to methods and URIs.
Your Javascript code mapped to methods and URIs.
Here is a sample using Respect\Rest:
$router->get('/users/*', function($userName) {
return MyDatabaseLayer::fetchUser($userName); //Illustrative
})->accept(
'application/json' => function($data) {
header('Content-type: application/json');
return json_encode($data);
}
);
Now the jQuery part:
$.getJSON('/users/alganet', function(user) {
alert(user.name);
});
You should use appropriate HTTP methods for different actions. Saving an user would be something like:
$router->post('/users/*', function($userName) {
return MyDatabaseLayer::saveUser($_POST['user']); //Illustrative
});
jQuery:
$.post('/users', $("$userform").serialize());
There are four main HTTP methods: GET, POST, PUT and DELETE. GET and POST are the most common ones.
There is a nice trivia: Both HTTP, REST and AMF were written by the same guy: Roy Fielding.
I would like to create a web service in PHP which can be consumed by different consumers (Web page, Android device, iOS device).
I come from a Microsoft background so am confortable in how I would do it in C# etc. Ideally I would like to be able to provide a REST service which can send JSON.
Can you let me know how I can achieve this in PHP?
Thanks
Tariq
I developed a class that is the PHP native SoapServer class' REST equivalent.
You just include the RestServer.php file and then use it as follows.
class Hello
{
public static function sayHello($name)
{
return "Hello, " . $name;
}
}
$rest = new RestServer(Hello);
$rest->handle();
Then you can make calls from another language like this:
http://myserver.com/path/to/api?method=sayHello&name=World
(Note that it doesn't matter what order the params are provided in the query string. Also, the param key names as well as the method name are case-insensitive.)
Get it here.
I would suggest you go for Yii it is worth of learning. You can easily establish it in this.
Web Service. Yii provides CWebService and CWebServiceAction to simplify the work of implementing Web service in a Web application. Web service relies on SOAP as its foundation layer of the communication protocol stack.
Easiest way in PHP is to use GET/POST as data-in and echo as data-out.
Here's a sample:
<?php if(empty($_GET['method'])) die('no method specified');
switch($_GET['method']){
case 'add': {
if(empty($_GET['a']) || empty($_GET['b'])) die("Please provide two numbers. ");
if(!is_numeric($_GET['a']) || !is_numeric($_GET['b'])) die("Those aren't numbers, please provide numbers. ");
die(''.($_GET['a']+$_GET['b']));
break;
}
}
Save this as test.php and go to http://localhost/test.php?method=add&a=2&b=3 (or wherever your webserver is) and it should say 5.
PHP does have native support for a SOAP server ( The SoapServer class manual shows it) and I've found it pretty simple to use.
Creating a REST style API is pretty easy if you use a framework. I don't want to get into a debate about which framework is better but CakePHP also supports output as XML and I'm pretty sure others will as well.
If you're coming from a Microsoft background just be careful about thinking about "datasets". They are a very specific Microsoft thing and have been a curse of mine in the past. It's probably not going to be an issue for you, but you may want to just see the differences between Microsoft and open implementations.
And of course PHP has a native json_encode() function.
You can check out this nice RESTful server written for Codeigniter, RESTful server.
It does support XML, JSON, etc. responses, so I think this is your library.
There is even a nice tutorial for this on the Tutsplus network -
Working with RESTful Services in CodeIgniter
You can also try PHP REST Data Services https://github.com/chaturadilan/PHP-Data-Services
You can use any existing PHP framework like CodeIgniter or Symfony or CakePHP to build the webservices.
You can also use plain PHP like disscussed in this example
I have a CakePHP Console Shell that works fine until a Model->afterFind() tries to add some data to the results which includes adding links, which doesn't seem to work while being called from the Console.
Is there a way to test in the Model->afterFind() callback function whether it's being called from a Console Shell, so that I can skip the troublesome section that I don't need anyway?
Thanks,
Ian
I'm not too sure whether there's a Cake way to do it, but you can do it via regular PHP
if(php_sapi_name() == 'cli' && empty(getClientIP())) {
//running via CLI
} else {
//running normally
}
It seems to me that you're breaking MVC best-practices if your business (model) layer is having adverse effects when run in different contexts. Whatever you're putting into Model->afterFind() should be completely agnostic to how the application is executed.
With that understood, the model layer of CakePHP is not at all aware of the execution context. One solution would be to deal with this by passing a flag to the model layer from the shell. ie:
At the top of app_model.php:
var $isShellContext = false;
Then, in your shell:
$this->Model->isShellContext = true;
And then in Model->afterFind():
if(!$this->isShellContext) {
// add links, etc
}